Issue
I have some regular expression validation that I use on email form, this is how it looks
this.customerForm = this.fb.group({
email: [null, {
Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$')],updateOn: 'blur'
}]
});
Validation work fine, but what i need is to make custom validator for this regular expression, any idea how to start, thanks
I have tried like this
properEmailValidator(): ValidatorFn {
const nameRe = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$/;
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { emailNotValid: { value: control.value } } : null;
};
}
But this does not work:(
Solution
When you define the expresion as a string, you have to escape the backslashes, as you properly did in the Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$')
.
But if you define the expresión as a proper RegExp
as you are doing in the validator function, you must not do it, as it would try to match it as a backslash character. So you need to modify your RegExp
as follows.
const nameRe = /^[^\s@]+@[^\s@]+\.[^\s@]{1,}$/;
Cheers
Answered By - akotech
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.