Abhinandan Khilari
Abhinandan Khilari

Reputation: 1077

Angular: Conditionally trigger selective form validations

Angular: Conditionally trigger selective form validations

I am using a reactive form with validations - 'required' and others like min, max, etc for the form fields. There are two buttons in the form - 'Save' and 'Submit'. Events on Save and Submit buttons will save data to intermediate state and submit it respectively according to the back end logic.

For Submit button, I have disabled it until the form is valid by property binding disabled attribute to form's invalid state. For Save button, I need to disable it if the fields are invalid according to the validations defined except 'required' validation. This is to check if any invalid inputs are entered.

For example, consider following form

this.registerForm = this.formBuilder.group({
    name: [''],
    email: ['', [Validators.required, Validators.email]],
})

In this case, I need to disable the button if invalid input is entered in the field, but enable it if it is left blank, that is ignore 'required' validation. The 'required' validation is required for disabling another button, that is Submit button.

How achieve such selective validations for different buttons?

Upvotes: 0

Views: 319

Answers (2)

robert
robert

Reputation: 6142

Another way is to setup your whole form without required validators. Then subscribe to:

this.registerForm.valueChanges.subscribe(val => {
  console.log(`Name is ${val.name} email is ${val.email}.`);
});

This will be called every time user makes any change. Here you can perform a simple required check like this:

if (val.name && val.email) { // simply to get is there any input (for required fields)
    this.submitValid = true;
}

In your html you can still bind to registerForm.valid but for save button. For submit button bind to "submitValid".

Upvotes: 1

Amir Arbabian
Amir Arbabian

Reputation: 3699

So, basically I've implemented it using two different methods, since you have validators only on email field, you can just check it directly, furthermore you can check which errors exactly it has, that is what I used:

  get isSaveValid(): boolean {
    let emailControl = this.registerForm.get('email');
    return emailControl.valid || 
      emailControl.hasError('required') &&
      Object.keys(emailControl.errors).length === 1;
  }

  get isSubmitValid(): boolean {
    let emailControl = this.registerForm.get('email');
    return emailControl.valid;
  }

and bindings:

  <button [disabled]="!isSaveValid">Save</button>
  <button [disabled]="!isSubmitValid">Submit</button>

IsSaveValid() only true when emailControl is valid or when it has required error and it's the only error. So in other words, user will be able to save bypassing required constraint, but all other validators will work (like email for example). There is an example on stackblitz. Hope that helps!

Upvotes: 1

Related Questions