Home > other >  set Angular form validator behaviour for particular validator
set Angular form validator behaviour for particular validator

Time:07-27

Is there any way we can set different validation behavior for different validators?

for example,

{
  field1: ['', [Validators.email, Validators.required]],
  field2: ['', Validators.required],
},

Here, field1 should validate the input on change, and field2 should validate the input on submit.

Is it possible to set behaviour for individual field of a form?

CodePudding user response:

Why would you want to let a user Submit something only for it to later fail? If a form lets me submit that means my form, as far as the front end is concerned, is valid.

However, if you want something like that then for field1:

form.controls['field1'].valueChanges.subscribe(x => {
...do your logic here, set the form as valid or not
}

for field2, you will have to set the form to run validations onSubmit:

https://stackoverflow.com/questions/55061066/how-to-validate-form-input-on-submit-in-angular-6#:~:text=You can use the updateOn,customer_id: new FormControl

How to user updateOn blur in FormBuilder

but in essence: field2: ['', {validators: Validators.required, updateOn: 'submit'}]

CodePudding user response:

formBuilder.group method's input controlsConfig has type as any, but as it uses FormControl constructor, we can use all the properties available in FormControl.

FormBuilder's group

group(controlsConfig: {
    [key: string]: any;
}, options?: AbstractControlOptions | {
    [key: string]: any;
} | null): FormGroup;

FormControl's constructor

constructor(
  formState?: any,
  validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
  asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
);

So we can make use of all available inputs for FormControl including in updateOn for each FormControl as below.

{
  field1: ['', [Validators.email, Validators.required]],
  field2: ['', {validators: Validators.required, updateOn: 'submit'}]
},
  • Related