如何使用Angular2表单验证指令

时间:2019-04-09 15:07:15

标签: angular angular-directive

我具有以下属性指令来执行表单验证。我的@NgModule将它包含在声明数组中。我的表单在组件的模板中。如何将appCarrierFormValidation属性添加到表单中,以便能够使用此指令并验证输入?

import { Directive } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Directive({
  selector: '[appCarrierFormValidation]'
})
export class CarrierFormValidationDirective {

  addCarrierForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }
  createForm() {
    this.addCarrierForm = this.fb.group({
      name: ['', Validators.required],
      email: ['',  [Validators.required, Validators.email]]
    })
  }
}

1 个答案:

答案 0 :(得分:1)

您可以像我在项目中使用的那样实现。

  import { FormControl } from '@angular/forms';

    export function appCarrierFormValidation(control: FormControl) {

        // change your logic to validate carrier
        let pattern = /[*\\/|":?><]/gi;
        //if validation fails, return error name & value of true
        if (pattern.test(control.value)) {
            return { validString: true };
        }
        //otherwise, if the validation passes, we simply return null
        return null;
    }

并使用

name: ['', [Validators.required, appCarrierFormValidation]],

如果要使用formGroup

public appCarrierFormValidation() : ValidatorFn{
       return (group: FormGroup): ValidationErrors => {
          const name= group.controls['name'];
          const email= group.controls['email'];
          // add your logic here
          if (name.value.length < 6 && email.value.indexOf('@') < 0) {
             email.setErrors({invalid: true});
          } else {
             email.setErrors(null);
          }
          return;
    };
 }

更新您的代码

 createForm() {
    this.addCarrierForm = this.fb.group({
      name: ['', Validators.required],
      email: ['',  [Validators.required, Validators.email]]
    })
    this.addCarrierForm .setValidators(this.appCarrierFormValidation())
  }