首页 > 其他 > 详细

[Angular] Create a custom validator for reactive forms in Angular

时间:2017-11-01 20:12:07      阅读:239      评论:0      收藏:0      [点我收藏+]

Also check: directive for form validation

 

User input validation is a core part of creating proper HTML forms. Form validators not only help you to get better quality data but they also guide the user through your form. Angular comes with a series of built-in validators such as required or maxLength etc. But very soon you have to build your own custom validators to handle more complex scenarios. In this lesson you‘re going to learn how to create such custom validators for Angular‘s reactive forms.

 

Basic validator is just a function.

import { ValidatorFn, AbstractControl, ValidationErrors } from @angular/forms;

export function nameValidator(name: string): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const isValid = control.value === ‘‘ || control.value === name;

    if (isValid) {
      return null;
    } else {
      return {
        nameMatch: {
          allowedName: name
        }
      };
    }
  };
}

 

Then you can use it with the validation in Reactvie form:

   import { nameValidator } from ./name.validator;
   
    this.form = this.fb.group({
      firstname: [‘‘, [Validators.required, nameValidator(someone)]]
    });

 

[Angular] Create a custom validator for reactive forms in Angular

原文:http://www.cnblogs.com/Answer1215/p/7768133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!