1

我想在 ngx-formly 中验证输入(电子邮件)。尝试使用下面的代码,但它确实有效

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'],
    }
}
4

1 回答 1

2

请用以下模式替换您的正则表达式模式。

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

此外,验证器和验证器消息必须在 app.module.ts 文件的 ng 模块部分中注册

 FormlyModule.forRoot({
  validators: [

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

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

],

请将您的代码与此https://stackblitz.com/edit/ngx-formly-custom-validator?file=src%2Fapp%2Fapp.component.ts进行比较

对于正则表达式模式,请参阅此https://www.w3resource.com/javascript/form/email-validation.php

于 2021-08-26T10:19:52.770 回答