Angular 2 - 反应式表单验证消息

时间:2017-04-13 04:06:27

标签: angular reactive-forms

我的目标是将所有验证消息放在组件而不是html文件

我有一个注册页面,下面是字段:

public buildRegisterForm() {
this.userForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
    retypeEmail: ['', Validators.required],
  }, { validator: formMatcherValidator('email', 'retypeEmail') }),
  passwordGroup: this.fb.group({
    password: ['', [Validators.required, strongPasswordValidator()]],
    retypePassword: ['', Validators.required],
  }, { validator: formMatcherValidator('password', 'retypePassword')}),
});
}

我按照本教程link来实现我想要的目标 将所有验证消息放在组件文件而不是html文件中。

export const validationMessages = {
'firstName': {
'required': 'Your first name is required.',
'minlength': 'Your first name must be at least 3 characters long.'
},
'lastName': {
'required': 'Your last name is required.',
'minlength': 'Your last name must be less than 50 characters long.'
},
'emailGroup': {
  'email': {
      'required': 'Your email is required',
      'pattern': 'Your login email does not seem to be a valid email address.'
     },
 'retypeEmail': {
      'required': 'Your retype email is required',
      'match': 'The email provided do not match.'
   },
},
'passwordGroup':{
     'password': {
         'required': 'Your password is required',
         'strongPassword': 'Your password must be between 8 - 15 characters and must contain at least three of the following: upper case letter, lower case letter, number, symbol.'
     },
   'retypePassword': {
       'required': 'Your retype password is required',
        'match': 'The password provided do not match.'
  }
}


onValueChanged方法

private onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;

// tslint:disable-next-line:forin
for (const field in this.formErrors) {
  // clear previous error message (if any)
  this.formErrors[field] = '';
  let control = form.get(field);
  // console.log("control", control.dirty);

  console.log("controlEmail", control);
  if (control && (control.dirty || control.touched) && control.invalid) {
    let messages = validationMessages[field];
    // tslint:disable-next-line:forin
    for (const key in control.errors) {
      this.formErrors[field] += messages[key] + ' ';
    }
  }
 }
}

当我有多个formBuider Group或嵌套Object时,这个方法不起作用。对此1的任何提示? 与此How to validate reactive forms with nested form groups?

类似

4 个答案:

答案 0 :(得分:7)

我看到它的方式,你需要在private final String track_id = MediaStore.Audio.Media._ID; private final String track_no = MediaStore.Audio.Media.TRACK; private final String track_name = MediaStore.Audio.Media.TITLE; private final String artist = MediaStore.Audio.Media.ARTIST; private final String artist_id = MediaStore.Audio.Media.ARTIST_ID; private final String duration = MediaStore.Audio.Media.DURATION; private final String album = MediaStore.Audio.Media.ALBUM; private final String composer = MediaStore.Audio.Media.COMPOSER; private final String year = MediaStore.Audio.Media.YEAR; private final String path = MediaStore.Audio.Media.DATA; private final String date_added = MediaStore.Audio.Media.DATE_ADDED; private final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; public Cursor getAllTracks(Context context) { // gets all tracks ContentResolver cr = context.getContentResolver(); final String[] columns = {track_id ,track_no, artist, track_name, album, duration, path, year, composer}; return cr.query(uri, columns, null, null, null); } - 方法中创建一个嵌套循环。由于你有很多嵌套组,我不打算复制它。但嵌套循环是通用的,因此它适用于所有组。但这是一个只有一个嵌套组而不是几个嵌套组的例子。我正在使用英雄的例子。

嵌套组名称为onValueChanged(data),其中的formcontrol称为group

因此,代码中使用的

child应该在formErrors内部child

group

因此,您必须记住在模板中添加验证时,您需要使用:

formErrors = {
  'name': '',
  'power': '',
  'group':{
    'child': ''
  }
};

验证邮件不会在<div *ngIf="formErrors.group.child"> {{ formErrors.group.child }} </div> 内,但就像其他验证邮件一样:

group

最后,修改后的validationMessages = { 'name': { 'required': 'Name is required.', }, 'power': { 'required': 'Power is required.' }, 'child': { 'required': 'Child is required.', } };

onValueChanges

最后,一个DEMO:)

Plunker

你必须记住,虽然在你的情况下这是有效的,但是如果在嵌套组中有嵌套组,这将不起作用,那么你必须在另一个循环中onValueChanged(data?: any) { if (!this.heroForm) { return; } const form = this.heroForm; // iterate toplevel of formErrors for (const field in this.formErrors) { // check if the field corresponds a formgroup (controls is present) if(form.get(field).controls ) { // if yes, iterate the inner formfields for(const subfield in form.get(field).controls) { // in this example corresponds = "child", reset the error messages this.formErrors[field][subfield] = ''; // now access the actual formfield const control = form.get(field).controls[subfield]; // validate and show appropriate error message if (control && control.dirty && !control.valid) { const messages = this.validationMessages[subfield]; for (const key in control.errors) { this.formErrors[field][subfield] += messages[key] + ' '; } } } } // does not contain a nested formgroup, so just iterate like before making changes to this method else { const control = form.get(field); this.formErrors[field] = ''; if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { this.formErrors[field] += messages[key] + ' '; } } } } } ,但你在这里没有遇到这个问题;)

答案 1 :(得分:3)

您还可以在原始onValueChanged方法旁边使用以下内容:

formErrors = {
  'name': '',
  'power': '',
  'group.child':''
};

validationMessages = {
  'name': {
    'required': 'Name is required.',
  },
  'power': {
    'required': 'Power is required.'
  },
  'group.child': {
    'required': 'Child is required.',
  }
};

onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

答案 2 :(得分:1)

我希望Nehal的解决方案有效,但我无法解决这个问题。在使用@ AJT_82代码后,想出了我的解决方案。我的需求确实来自于想要将密码作为一个群体进行检查,而他的解决方案并没有涵盖这一点。所以,我已经包含了我用来创建适合我的完整解决方案的其他工具。

我发现我在2中使用的方法不再起作用后,尝试在角度4中验证密码确认时遇到了这个问题。关于angular.io的信息对此没有多大帮助,因为很多信息在他们的文档的不同区域分散。

因此,为了澄清,这遵循Angular的反应形式方法。我写这个是为了在一个实例中验证密码,我也有其他验证限制(密码必须在4到24个字符之间,是必需的,等等)。通过一些小的调整,这种方法也适用于电子邮件确认。

首先,为了比较组的验证器,html表单必须具有使用 formGroupName =&#34;标识的子组。 &#34; 标识符。这是在主 [formGroup] 标识符内。比较输入必须位于此 formGroupName 标记的元素内。就我而言,它只是一个div。

<div class="title">Hero Registration Form</div>
<form [formGroup]="regForm" id="regForm" (ngSubmit)="onSubmit()">
    <div class="input">
        <label for="heroname">Heroname</label> <input type="text"
            id="heroname" class="form-control" formControlName="heroname"
            required />
        <div *ngIf="formErrors.heroname" class="hero-reg-alert">{{
            formErrors.heroname }}</div>
    </div>
    <div class="input">
        <label for="email">Email</label> <input type="email" id="email"
            class="form-control" formControlName="email" required />
        <div *ngIf="formErrors.email" class="hero-reg-alert">{{
            formErrors.email }}</div>
    </div>
    <div formGroupName="password">
        <div class="input">
            <label for="password1">Password</label> <input type="password"
                id="password1" class="form-control" formControlName="password1"
                required />
            <div *ngIf="formErrors.password.password1" class="hero-reg-alert">
                {{ formErrors.password.password1 }}</div>
        </div>
        <div class="input">
            <label for="password2">Re-Enter Password</label> <input
                type="password" id="password2" class="form-control"
                formControlName="password2" required />
            <div
                *ngIf="formErrors.password.password2 || formErrors.password.password"
                class="hero-reg-alert">{{ formErrors.password.password }} {{
                formErrors.password.password2 }}</div>
        </div>
    </div>
    <button type="submit" [disabled]="!regForm.valid">
        <span id="right-btntxt">SUBMIT</span>
    </button>
</form>

您可能会注意到我将formErrors的子值设为

formErrors.password.password
formErrors.password.password1
formErrors.password.password2

这些都是在我的代码中构建的......

  formErrors = {
    'username': '',
    'email': '',
    'password': {
      'password': '',
      'password1': '',
      'password2': ''
    }
  };

我用这种方式构建它&#39; password1&#39;和密码2&#39;为每个字段保留我的formErrors,而密码是&#39;在不匹配的情况下(两个输入的密码不相等)保存我的错误。

这里可能是onValueChanged()公式。它检查字段是否是FormGroup的实例。如果是这样,它首先检查该字段组的自定义验证(将它们存储在&#39; this.formErrors [field] [field]&#39;)中,然后继续处理子字段验证。如果它不是FieldGroup的实例,则根据angular.io的指导文档中的示例处理验证。

  onValueChanged(data?: any) {
    if (!this.regForm) {return;}
    const form = this.regForm;

    for (const field in this.formErrors) {
      const formControl = form.get(field);
      if (formControl instanceof FormGroup) {
        this.formErrors[field][field] = '';
        // check for custom validation on field group
        const control = form.get(field);
        // handle validation for field group
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            this.formErrors[field][field] += messages[key] + ' ';
          }
        }
        // handle validation for subfields
        for (const subfield in formControl.controls) {
          console.log('SUBFIELD', subfield);
          this.formErrors[field][subfield] = '';
          const control = formControl.controls[subfield];
          if (control && control.dirty && !control.valid) {
            const messages = this.validationMessages[subfield];
            for (const key in control.errors) {
              this.formErrors[field][subfield] += messages[key] + ' ';
            }
          }
        }
      } 
        // alternate validation handling for fields without subfields (AKA not in a group)
      else {
        const control = form.get(field);
        this.formErrors[field] = '';
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            this.formErrors[field] += messages[key] + ' ';
          }
        }
      }
    }
  }

通过为FieldGroup提供一个具有自己名称的子字段,我们可以将验证存储在FieldGroup上。尝试使用常规onValueChange代码覆盖行上的子字段...

    this.formErrors[field] = '';

不提供存储FieldGroup验证的位置要么覆盖子字段,要么不处理FieldGroup。

如果需要,可以使用buildFomr();

构建表单
 buildForm(): void {
    this.regForm = this.formBuilder.group({
      'username': [this.registerUser.username, [
        Validators.required,
        Validators.minLength(4),
        Validators.maxLength(24)
      ]
      ],
      'email': [this.registerUser.email, [
        Validators.email,
        Validators.required
      ]
      ],
      'password': this.formBuilder.group({
        'password1': [this.registerUser.password, [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(24)
        ]
        ],
        'password2': ['', [
          Validators.required
        ]
        ]
      }, {validator: this.passwordMatchValidator})
    }); // end buildForm

    this.regForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

这是自定义验证功能......

  passwordMatchValidator(control: FormGroup): {[key: string]: any} {
    return control.get('password1').value !== control.get('password2').value ? {mismatch: true} : null;
  }

答案 3 :(得分:0)

 public morningForm:FormGroup;

 constructor(public fb: FormBuilder) { }
 ngOnInit() {
 this.morningForm = this.fb.group({
      'country': [''],
      'city' : [''],
      'phone': ['']
    });
    this.setValidators();
}
private setValidators() {
    let me = this;
    let status = false;
    me.morningForm.valueChanges.subscribe(fieldObj => {
      for (const fieldName in fieldObj) {
      // IF ENTER OR FIND THE VALUE THEN ALL FIELD SET AUTO REQUIRED VALIDATION.
        if (fieldObj[fieldName] != '') {
          status = true;
          break;
        }
      }
    });
    this.setRequiredField(status)
  }

  private setRequiredField(status:any) {
    let me = this;
    let country = me.morningForm.get('country');
    let city = me.morningForm.get('city');
    let phone = me.morningForm.get('phone');

    country.setValidators(null);
    city.setValidators(null);
    phone.setValidators(null);
    if (status) {
      country.setValidators([Validators.required]);
      city.setValidators([Validators.required]);
      phone.setValidators([Validators.required]);
    }
    country.updateValueAndValidity();
    city.updateValueAndValidity();
    phone.updateValueAndValidity();
  }