1

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?

Prajwal
  • 3,930
  • 5
  • 24
  • 50

2 Answers2

0

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%20can%20use%20the%20updateOn,customer_id%3A%20new%20FormControl

How to user updateOn blur in FormBuilder

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

SomeStudent
  • 2,856
  • 1
  • 22
  • 36
  • Thanks for answering, I figured out that we can pass pretty much everything required for `FormControl` in the form of array. I have added an explanatory answer for the same. Both the questions you have listed doesn't answer how to set *different* behaviours for multiple inputs. However, your code snippet for `field2` does answer my question. There's no need to listen to `field1` changes as form's default behaviour is update on change. – Prajwal Jul 26 '22 at 15:25
0

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'}]
},
Prajwal
  • 3,930
  • 5
  • 24
  • 50