0

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;
  }

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

So we cannot use directly on net_amount for example ?
yes i will edit my post with that for you aswell gime 10 min

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.