Formly Email custom validation with pattern does not works

3k Views Asked by At

I want to validate input (email) in ngx-formly. tried with the code below but it dint worked

app.module.ts

export function EmailValidator(control: FormControl): ValidationErrors {
    return /^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$/.test(control.value) ? null : { 'email': true };
}

export function EmailValidatorMessage(err, field: FormlyFieldConfig) {
    return `"${field.formControl.value}" is not a valid Email Address`;
}

app.component.ts

{
    key: 'email',
    type: 'input',
    className: 'flex-3',
    templateOptions: {
        type: 'text',
        label: 'Email',
        placeholder: 'Email',
    },
    validators: {
        validation: ['email'],
    }
}
1

There are 1 best solutions below

0
On

Please replace your regex pattern with the following pattern.

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

Also the validator, and validator message has to be registered in your ng module section in your app.module.ts file

 FormlyModule.forRoot({
  validators: [

    { name: "email", validation: EmailValidator }
,],
  validationMessages: [

    { name: "email", message: EmailValidatorMessage }
  ]
})

],

please compare your code with this https://stackblitz.com/edit/ngx-formly-custom-validator?file=src%2Fapp%2Fapp.component.ts

For regex pattern please refer this https://www.w3resource.com/javascript/form/email-validation.php