简体   繁体   中英

Adding custom validators to FormArray in Angular reactive forms

I have a reactive form like this

this.form = this.fb.group({
      items: this.fb.array(
        [
          this.fb.group({
            net_amount: [
              null,
              Validators.compose([
                Validators.required,
                Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
                isValidNumericValue
              ])
            ],
          })
        ],
        Validators.required
      ),
      substances: this.initAdditives(),
      net_total: [
        this.currentProduct.net_total || null,
        [
          Validators.required,
          Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
          isValidNumericValue
        ]
      ]
    });

isValidNumericValue is a custom validator that checks whether a number is greater than zero. The problem is the validator works outside FormArray but not inside.

  export function isValidNumericValue(AC: AbstractControl) {
    if (AC.value <= 0) {
      return { numericError: true };
    }
    return null;
  }

i think your problem is , since you want to apply the validator to the fb.group you should do like this:

this.fb.group({
      net_amount: [null, [Validators.required, Validators.pattern('^[0-9]+(.?[0-9]+)?$')]
    ],
  }, { validator: isValidNumericValue })

I will post you here a form with both validation "Group" and "Single":

First you need to create validation rules:

function emailMatch(c: AbstractControl): {[key: string]: boolean} | null {
    let email = c.get('email');
    let confirmEmail = c.get('confirmEmail');

    if (email.value === confirmEmail.value) {
        return null;
    }
    return { 'match': true };
 }

This validation i will use for a star rating in a product for example:

function MyRangeFunction (min: number, max: number): ValidatorFn {
    return  (c: AbstractControl): {[key: string]: boolean} | null => {
        if (ifYouGotError) {
            return { 'range': true };
        };
        return null;
    };
}

Now my form is this:

this.myForm = this.fb.group({
            emailGroup: this.fb.group({
                email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
                confirmEmail: ['', Validators.required],
            }, {validator: emailMatch}),

            rating: ['', MyRangeFunction (1, 5)],
        });

I think here you have all covered about validation!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM