角度表单验证:比较两个字段

时间:2017-09-12 16:20:56

标签: forms angular validation angular-forms angular-validation

在Angular 4应用程序中,如何验证进行比较的表单的两个字段?

例如,我们假设我的表单包含startDateendDate个日期字段,我想确保endDate必须大于startDate

2 个答案:

答案 0 :(得分:11)

如果要实现包含一个或多个兄弟(窗体)控件的验证,则必须在高于/高于同级控件的级别上定义验证器函数。例如:

ngOnInit() {
 this.form = this.formbuilder.group({
  'startDate' = ['', [<control-specific-validations>]],
  'endDate' = ['', [<control-specific-validations>]]
 }, { validator: checkIfEndDateAfterStartDate }
 });
}

然后在组件类的定义之外(在同一个文件中),定义函数checkIfEndDateAfterStartDate

export function checkIfEndDateAfterStartDate (c: AbstractControl) {
 //safety check
 if (!c.get('startDate').value || !c.get('endDate').value) { return null }
 // carry out the actual date checks here for is-endDate-after-startDate
 // if valid, return null,
 // if invalid, return an error object (any arbitrary name), like, return { invalidEndDate: true }
 // make sure it always returns a 'null' for valid or non-relevant cases, and a 'non-null' object for when an error should be raised on the formGroup
}

此验证会通过向FormGroup的{​​{1}}添加错误标记(此处为invalidEndDate}来使true无效。如果您希望在任何兄弟控件上设置特定错误,则可以使用FormGroup之类的内容手动设置formControl上的错误标记。如果您这样做,请务必通过将错误设置为c.get('endDate').setErrors({ invalidEndDate: true })null来确保将其清除为有效案例。

可以看到类似验证的现场演示here

答案 1 :(得分:0)

试试这个

export class validationComponent implements OnInit {
     private testForm:FormGroup;

     constructor(private fb: FormBuilder) {

     }

     ngOnInit() {
         this.testForm = this.fb.group({
           'startDate': ['', [Validators.required]],
           'endDate': ['', [Validators.required]]
        });

       this.subscribeDateChanges();
    }

    subscribeDateChanges() {
        const startDateChanges = (<any>this.testForm).controls.startDate.valueChanges;
        const endDateChanges = (<any>this.testForm).controls.endDate.valueChanges;

        startDateChanges.subscribe(start => {
             this.testForm.controls['endDate'].
               setValidators(
                [Validators.required,
                CustomValidators.minDate(this.toYYYYMMDD(start))]);
        this.validateDates();
       });

       endDateChanges.subscribe(end => {
               this.validateDates();
         });
     }

   dateError: boolean = false;
   validateDates(): void{
       let startDate = this.testForm.controls['startDate'].value;
       let endDate = this.testForm.controls['endDate'].value;
       if(endDate && startDate){
           this.dateError = endDate <= startDate;
        }
    }

   toYYYYMMDD(d:Date): string {
       d = new Date(d)
       var yyyy = d.getFullYear().toString();
       var mm = (d.getMonth() + 101).toString().slice(-2);
       var dd = (d.getDate() + 100).toString().slice(-2);
       return yyyy + '-' +  mm + '-'  + dd;
   }

基于 dateError 布尔值显示错误消息msg