Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'includes')

huangapple go评论75阅读模式
英文:

Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'includes')

问题

I am new to angular and was learning how to create custom directives. I was handling some email validations in email-validation.directive.ts and found that I am getting this error.

email-validation.directive.ts

import { Directive } from '@angular/core';
import {
  AbstractControl,
  NG_VALIDATORS,
  ValidationErrors,
  Validator,
} from '@angular/forms';

@Directive({
  selector: '[appEmailValidation]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: EmailValidationDirective,
      multi: true,
    },
  ],
})
export class EmailValidationDirective implements Validator {
  count = 0;
  validate(control: AbstractControl<any, any>): ValidationErrors | null {
    const value = control.value as string;

    if (!value.includes('@') && !value.includes('.com')) {
      return {
        invalidEmail: true,
      };
    }
    return null;
  }
  constructor() {}
}

Here is my code and condition of my directive. I want to check if the email contains @ and .com keywords and if it doesn't, I want to set invalidEmail as true.

Main Component Code

register.component.html

<form #registerForm="ngForm" class="form-container" (ngSubmit)="postData(registerForm)">
  <mat-grid-list cols="1" rowHeight="100vh">
    <mat-grid-tile>
      <div class="example-container">
        <mat-form-field hintLabel="Max 20 characters" appearance="fill" class="width-50">
          <mat-label>First Name</mat-label>
          <input #fname minlength="3" maxlength="20" required [(ngModel]="ad.firstName" type="text" name="firstName"
            matInput placeholder="Enter Your Firstname">
          <mat-hint align="end">{{fname.value.length}}/20</mat-hint>
        </mat-form-field>

        <mat-form-field hintLabel="Max 20 characters" appearance="fill" class="width-50 ml-2">
          <mat-label>Last name</mat-label>
          <input #lname minlength="3" maxlength="20" required [(ngModel]="ad.lastName" name="lastName" type="text"
            matInput placeholder="Enter your Lastname">
          <mat-hint align="end">{{lname.value.length}}/20</mat-hint>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill" class="width-100">
          <mat-label>City</mat-label>
          <input minlength="3" maxlength="20" required [(ngModel]="ad.city" name="city" type="text" matInput
            placeholder="Enter your City">
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill" class="width-100">
          <mat-label>Age</mat-label>
          <input min="1" max="100" required [(ngModel]="ad.age" name="age" type="number" matInput placeholder="Age">
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill" class="width-100">
          <mat-label>Username</mat-label>
          <input appEmailValidation #user="ngModel" required [(ngModel]="ad.username" name="username" matInput
            placeholder="Enter your username">
          <mat-hint color="warn"></mat-hint>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill" class="width-100">
          <mat-label>Enter password</mat-label>
          <input required [(ngModel]="ad.password" name="password" matInput [type]=" hide ? 'password' : 'text'">
          <button mat-icon-button matSuffix (click)=" hide=!hide" [attr.aria-label]="'Hide password'"
            [attr.aria-pressed]="hide">
            <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
          </button>
        </mat-form-field>
        <button [disabled]="registerForm.invalid" mat-raised-button color="primary">Submit</button>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</form>
{{user.errors | json}}

When I am running the code, I am getting this error Cannot read properties of null.

英文:

I am new to angular and was learning how to create custom directives. I was handling some email validations in email-validation.directive.ts and found that i am geting this error

email-validation.directive.ts

import { Directive } from &#39;@angular/core&#39;;
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from &#39;@angular/forms&#39;;
@Directive({
selector: &#39;[appEmailValidation]&#39;,
providers: [
{
provide: NG_VALIDATORS,
useExisting: EmailValidationDirective,
multi: true,
},
],
})
export class EmailValidationDirective implements Validator {
count = 0;
validate(control: AbstractControl&lt;any, any&gt;): ValidationErrors | null {
const value = control.value as string;
if (!value.includes(&#39;@&#39;) &amp;&amp; !value.includes(&#39;.com&#39;)) {
return {
invalidEmail: true,
};
}
return null;
}
constructor() {}
}

Here is my code and condition of my directive. I want to check if the email contains @ and .com keywords and if id doesn't I want to set invalidEmail as true
Main Component Code

register.component.html

&lt;form #registerForm=&quot;ngForm&quot; class=&quot;form-container&quot; (ngSubmit)=&quot;postData(registerForm)&quot;&gt;
&lt;mat-grid-list cols=&quot;1&quot; rowHeight=&quot;100vh&quot;&gt;
&lt;mat-grid-tile&gt;
&lt;div class=&quot;example-container&quot;&gt;
&lt;mat-form-field hintLabel=&quot;Max 20 characters&quot; appearance=&quot;fill&quot; class=&quot;width-50&quot;&gt;
&lt;mat-label&gt;First Name&lt;/mat-label&gt;
&lt;input #fname minlength=&quot;3&quot; maxlength=&quot;20&quot; required [(ngModel)]=&quot;ad.firstName&quot; type=&quot;text&quot; name=&quot;firstName&quot;
matInput placeholder=&quot;Enter Your Firstname&quot;&gt;
&lt;mat-hint align=&quot;end&quot;&gt;{{fname.value.length}}/20&lt;/mat-hint&gt;
&lt;/mat-form-field&gt;
&lt;mat-form-field hintLabel=&quot;Max 20 characters&quot; appearance=&quot;fill&quot; class=&quot;width-50 ml-2&quot;&gt;
&lt;mat-label&gt;Last name&lt;/mat-label&gt;
&lt;input #lname minlength=&quot;3&quot; maxlength=&quot;20&quot; required [(ngModel)]=&quot;ad.lastName&quot; name=&quot;lastName&quot; type=&quot;text&quot;
matInput placeholder=&quot;Enter your Lastname&quot;&gt;
&lt;mat-hint align=&quot;end&quot;&gt;{{lname.value.length}}/20&lt;/mat-hint&gt;
&lt;/mat-form-field&gt;
&lt;br&gt;
&lt;mat-form-field appearance=&quot;fill&quot; class=&quot;width-100&quot;&gt;
&lt;mat-label&gt;City&lt;/mat-label&gt;
&lt;input minlength=&quot;3&quot; maxlength=&quot;20&quot; required [(ngModel)]=&quot;ad.city&quot; name=&quot;city&quot; type=&quot;text&quot; matInput
placeholder=&quot;Enter your City&quot;&gt;
&lt;/mat-form-field&gt;
&lt;br&gt;
&lt;mat-form-field appearance=&quot;fill&quot; class=&quot;width-100&quot;&gt;
&lt;mat-label&gt;Age&lt;/mat-label&gt;
&lt;input min=&quot;1&quot; max=&quot;100&quot; required [(ngModel)]=&quot;ad.age&quot; name=&quot;age&quot; type=&quot;number&quot; matInput placeholder=&quot;Age&quot;&gt;
&lt;/mat-form-field&gt;
&lt;br&gt;
&lt;mat-form-field appearance=&quot;fill&quot; class=&quot;width-100&quot;&gt;
&lt;mat-label&gt;Username&lt;/mat-label&gt;
&lt;input appEmailValidation #user=&quot;ngModel&quot; required [(ngModel)]=&quot;ad.username&quot; name=&quot;username&quot; matInput
placeholder=&quot;Enter your username&quot;&gt;
&lt;mat-hint color=&quot;warn&quot;&gt;&lt;/mat-hint&gt;
&lt;/mat-form-field&gt;
&lt;br&gt;
&lt;mat-form-field appearance=&quot;fill&quot; class=&quot;width-100&quot;&gt;
&lt;mat-label&gt;Enter password&lt;/mat-label&gt;
&lt;input required [(ngModel)]=&quot;ad.password&quot; name=&quot;password&quot; matInput [type]=&quot; hide ? &#39;password&#39; : &#39;text&#39;&quot;&gt;
&lt;button mat-icon-button matSuffix (click)=&quot; hide=!hide&quot; [attr.aria-label]=&quot;&#39;Hide password&#39;&quot;
[attr.aria-pressed]=&quot;hide&quot;&gt;
&lt;mat-icon&gt;{{hide ? &#39;visibility_off&#39; : &#39;visibility&#39;}}&lt;/mat-icon&gt;
&lt;/button&gt;
&lt;/mat-form-field&gt;
&lt;button [disabled]=&quot;registerForm.invalid&quot; mat-raised-button color=&quot;primary&quot;&gt;Submit&lt;/button&gt;
&lt;/div&gt;
&lt;/mat-grid-tile&gt;
&lt;/mat-grid-list&gt;
&lt;/form&gt;
{{user.errors | json}}

When I am running the code i am getting this error
Cannot read properties of null

答案1

得分: 1

请修改此条件:

if (!value || (!value.includes('@') && !value.includes('.com'))) {
  return {
    invalidEmail: true,
  };
}

因为在您的情况下,valuenull,我认为 null 也是电子邮件的无效值。

英文:

simply edit this condition:

if (!value || ( !value.includes(&#39;@&#39;) &amp;&amp; !value.includes(&#39;.com&#39;))) {
return {
invalidEmail: true,
};
}

Because in your case value is null and I believe that null is also an invalid value for email.

huangapple
  • 本文由 发表于 2023年2月19日 15:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定