Reputation: 55
I am new to angular need your help. I am trying to validate a email using reactive form onkeyup event.
registerform:any;
ngOnInit(): void {
this.registerform = new FormGroup({
"emailId": new FormControl(null,[Validators.required,Validators.email])
});
}
get emailid() { return this.registerform.get('emailId');}
<form [formGroup]="registerform" (ngSubmit) = "submitData()">
<input type="text" formControlName="emailId" placeholder="email">
<div *ngIf="emailid.invalid && (emailid.touched || emailid.dirty)">
<span class="myerror" name="err" *ngIf="emailid.errors?.required">*Email is required.</span>
<span class="myerror" name="err" *ngIf="emailid.errors?.email">*Email is not valid.</span>
</div>
</form>
Upvotes: 0
Views: 2570
Reputation: 545
Instead of using from Validators you can create angular directive
@Directive({
selector: '[appEmailValidator]',
providers: [
{ provide: NG_VALIDATORS, useExisting: EmailValidator, multi: true }
]
})
export class EmailValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = validateEmailFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
// validation function
function validateEmailFactory(): ValidatorFn {
return (c: FormControl) => {
if (c.value) {
// tslint:disable-next-line:max-line-length
const isValidEmail = c.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
const message = {
emailCheck: {
message: 'Email address is invalid'
}
};
return isValidEmail ? null : message;
}
};
}
Now use this directive in your input field
<input type="text" id="lpd-email-input" formControlName="email"
class="form-control"
[placeholder]="Email address" autocomplete="none" appEmailValidator/>
Upvotes: 1