我们如何在Angular中一个接一个地显示表单错误验证

时间:2018-11-29 09:42:40

标签: angular angular2-form-validation

我是angular的新手,我创建了一个自定义EmailDomainError验证器类,并且可以正常工作。

但是问题是电子邮件域错误与电子邮件验证错误消息一起显示,我该如何解决此问题,我确实感到困惑,请问有人可以帮助我

我认为我必须在EmailDomainError类中检查电子邮件格式是否正确,如果我认为正确的方式和完整的代码-https://stackblitz.com/edit/angular-bvihqj

ngOnInit

 ngOnInit() {

    this.employeeForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(10)]],
      contactPreference: ['email'],
      email: ['', [Validators.required, Validators.email, emailDomainError]],
      phone: [''],
      skills: this.fb.group({
        skillName: ['', [Validators.required]],
        experienceInYears: ['', [Validators.required]],
        proficiency: ['', [Validators.required]]
      })
    });

该对象包含此表单的所有验证消息

 formErrors = {
    'fullName': '',
    'email': '',
    'phone': '',
    'skillName': '',
    'experienceInYears': '',
    'proficiency': ''
  };


     validationMessages = {
        'fullName': {
          'required': 'Full Name is required.',
          'minlength': 'Full Name must be greater than 2 characters.',
          'maxlength': 'Full Name must be less than 10 characters.'
        },
        'email': {
          'required': 'Email is required.',
          'email': 'Valid Email id is required.',
          'emailDomainError': 'Email domain should be karvy.com'
        },
        'phone': {
          'required': 'Phone number is required.'
        },
        'skillName': {
          'required': 'Skill Name is required.',
        },
        'experienceInYears': {
          'required': 'Experience is required.',
        },
        'proficiency': {
          'required': 'Proficiency is required.',
        },
      };

emailDomainError

function emailDomainError(control: AbstractControl): { [key: string]: any } | null {
  const email: string = control.value;
  const domain: string = email.substring(email.lastIndexOf("@") + 1);
  if (email === '' || domain === "karvy.com") {
    return null;
  } else {
    return { "emailDomainError": true };
  }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

尊敬的AbhiRam,我在这里更新您的代码是Here

的链接

在表单组中,像这样

  func updateSearchResults(for searchController: 
       UISearchController) {

   if (searchController.searchBar.text?.characters.count)! > 0 {
       guard let searchText = searchController.searchBar.text, 
       searchText != "" else {
           return
       }
       usersDataFromResponse.removeAll()
       let searchPredicate = NSPredicate(format: "userName 
        CONTAINS[C] %@", searchText)

       usersDataFromResponse = (filteredArray as 
        NSArray).filtered(using: searchPredicate)

       print ("array = \(usersDataFromResponse)")

       self.listTableView.reloadData()
    }


  }

功能代码更改 *

[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyContextContext : DbContext
{
}