Search code examples
javascriptangularangular6angular-validation

Any simple way to apply one validation rule to all fields by Angular 6


Consider a data model contains 20 string fields with different name ("name", "address", "company".. etc ), mapped to Angular front end as 20 input fields. Now the requirement asks to validate each fields that prevent user submit the form if any fields contain special characters.

I can work out the regex pattern but just wondering any simple way to do one validator to all fields.


Solution

  • There is a simple solution for this by using for example only one async validator.

    For example you can group all the fields that we should verify whenever one field change in a subform and then apply a validator to them.

    Example:

    this.mySubForm = this.fb.group({
        field1: ['', [Validators.required]],
        field2: ['', [Validators.required]],
        ...
        field20: ['', [Validators.required]]
    }, this.validatorAllFields.bind(this)
    
       });
    

    And define the async validator this way:

    validatorAllFields(control: FormGroup): any {
      if (control) {
          if(control.value.field1 don't contain special char … &&
             control.value.field2 don't contain special char … &&
             …
             control.value.field20 don't contain special char &&)
             //validation is ok in this case
             return null;
          else
             //validation fails here...
             return {'formInvalid': 'true'}
      } else {
          return null;
        }
      }
    

    You can do this without any additional package and it will work. just implement the: do not have any special char for each control, it should be the same function for example.

    You can use formGroupName for the sub form, or even avoid the use of a sub form if you want.