Does anybody know how to trigger Form Validators in Angular2?

angular 2 validation on button click
angular input validation without form
angular 4 form validation on submit
typescript form validation
reactive form validation in angular 7
angular template form validation
angular 9 form validation
angular form validation

In angular2 I want to trigger Validators for some controls when a another control is changed. Is there some way that I can just tell the form to re-validate? Better still, can I request validation of specific fields?

Example: Given Checkbox X and input P. Input P has a validator that behaves differently based on the model value of X. When X is checked/unchecked I need to invoke the validator on P. The Validator on P will look at the model to determine the state of X and will validate P accordingly.

Here's some code:

constructor(builder: FormBuilder) {
    this.formData = { num: '', checkbox: false };

    this.formGp = builder.group({
        numberFld: [this.formData.num, myValidators.numericRange],
        checkboxFld: [this.formData.checkbox],
    });
}

this.formGp.controls['checkboxFld'].valueChanges.observer({
    next: (value) => {
        // I want to be able to do something like the following line:
        this.formGp.controls['numberFld'].validator(this.formGp.controls['numberFld']);
    }
});

Anybody have a solution? Thanks!

I don't know if you are still looking for an answer, so here is my suggestions:

Have a look at this: Angular 2 - AbstractControl

I think what you could do is following:

this.formGp.controls['checkboxFld'].valueChanges.observer({
    next: (value) => {
       this.formGp.controls['numberFld'].updateValueAndValidity();
    }
});

This should trigger and run the validators. Furthermore the state gets updated as well. Now you should be able to consult the checkbox value within your validator logic.

Hope this helps!

EDIT: Updated link and example. Code changed while I was writing my answer.

EDIT_2: alpha.48 changes the EventEmitter.observer to EventEmitter.subscribe!

EDIT_3: Changed link to the actual implementation, added link to the documents

Validaton-Guide

FormControl Documentation

In angular2 I want to trigger Validators for some controls when a another control is changed. The Validator on P will look at the model to determine the state of X and will validate P accordingly. Here's some code: constructor(builder: FormBuilder) { this. Now i want to trigger the form validation if the user clicks on the submit button. In the examples i have found so far the submit button is disabled as long as the form is invalid but i want to have the submit button always enable and when the user clicks on submit the form should be validated.

with my ControlGroup I do this because I have errors divs checking if touched

for (var i in this.form.controls) {
  this.form.controls[i].markAsTouched();
}

(this.form is my ControlGroup)

So, someone who has worked with forms in AngularJS will be very familiar with this That being said, you can activate the template-driven forms as following: Although this Angular 4 form is declared, at this point it doesn't know of any Angular 4 <title>angular2 playground</title> <link rel="stylesheet" href="style.​css"  Does anybody know how to trigger Form Validators in Angular2? (4) In angular2 I want to trigger Validators for some controls when a another control is changed. Is there some way that I can just tell the form to re-validate? Better still, can I request validation of specific fields?

With the help of this blog

blog link

I have came across a solution with the combine of Nightking answer

Object.keys(this.orderForm.controls).forEach(field => {
       const control = this.orderForm.get(field);
       control.updateValueAndValidity();

});

this.orderForm is the form group

It's a requirement to use the <form> element for Angular 2 validation to work. Otherwise, there will be no submit event and you cannot catch errors for each input. form has the following The (ngSubmit) is pretty much an event to trigger the onSubmit(f) You just need to know how to validate each input and display the error. does not require traversing through the form's controls and modifying their status; does not require adding some additional submitted property to each control; does not require any additional form validation handling in the ngSubmit-binded onSubmit methods; does not combine template-driven forms with reactive forms; form-base.component:

There are more elegant ways of modeling this behavior - for example, putting your state into a ReplaySubject and observing that, and then using async validators observing the state - but the pseudo-coded approach below should work. You simply observe the value changes in the checkbox, update the model as appropriate, then force a re-validation of the numberFld with the updateValueAndValidity cal.

constructor(builder: FormBuilder) {
  this.formData = { num: '', checkbox: false };
  const numberFld = builder.control(this.formData.num, myValidators.numericRange);

  const checkbox = builder.control(this.formData.checkbox);
  checkbox.valueChanges.map(mapToBoolean).subscribe((bool) => {
    this.formData.checked = bool;
    numberFld.updateValueAndValidity(); //triggers numberFld validation
  });

  this.formGp = builder.group({
      numberFld: numberFld,
      checkboxFld: checkbox
  });
}

See also Creating and using a custom asynchronous validator with Promises validator operates under the assumption that the validity of a certain input can be quite often if form validation is bound to rapid-fire events such as keypresses. It just so happens that some of the behavior can involve a somewhat long delay so the form locking is required - both to lock the form and also indicate the form has been submitted. Fixing the locking behavior so that the form is locked when angular.element ('form').trigger ('submit') is called would be great.

This did the trick for me

this.myForm.markAllAsTouched();

If you are new to Angular 2 model-driven forms, please refer to Using Angular 2's Model-Driven Forms to get to know the basics. Related Video Course: Angular v2+ Forms and Validation. Angular 2 - Conditional Validation (final) updated the validation rules of each field. We did not trigger any updates. Validating input in reactive forms link. In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.

So, let's see how we can fire validation errors on-blur in Angular 2. Basically, we want to leverage the touch property of form controls and use to  If this pattern does not satisfy your business needs, you can use Validators.pattern() to validate the value against a different pattern. Usage Noteslink Validate that the field matches a valid email patternlink

Kevin Hennessy. We then add a validation message for each of the video input fields. Again, the syntax is verbose but easy enough to understand. Saving. the​. form. The final step in building out our model-driven form is to handle saving the form. When we This method sets submitted to true, which will trigger the  How do we get there? Angular has an internal mechanism to execute validators on a form control. It maintains a multi provider for a dependency token called NG_VALIDATORS. If you’ve read our article on multi providers in Angular, you know that Angular injects multiple values for a single token that is used for a multi provider. If you haven’t, we highly recommend checking it out as the rest of this article is based on it.

⁠⁠⁠⁠Do you want to receive a desktop notification when new content is published? In this tutorial we will look at how to implement forms with Angular 2 We'll see how to introduce validation to our forms, and even create a Clone the project and fire up the server to use it with the code samples here. Validators. Carrying on from the model-driven form we started in the previous lecture. Our form is valid all the time, regardless of what input the user types into the controls. Validators are rules which an input control has to follow. If the input doesn’t match the rule then the control is said to be invalid.

Comments
  • Are you just trying to enable/disable the validation based on the value of X? What sort of validators are you using? You can cause validators to execute based on a condition in your scope, but I'm not sure if that approach will work for you. See: stackoverflow.com/questions/21370006/…
  • @stephen.vakil - I'm using angular2.
  • @Bonneville could you please explain how you are passing the checkbox state to the validator function?
  • Thanks @Nightking for the suggestion, I'll try it out. Note that your link isn't working.
  • @Bonneville Thanks for the information. They extracted the form code to the common namespace. Things changing a bit to fast :). I've updated the link to the source.
  • I finally got around to using this piece of code and it seems to be working for me. Thanks! BTW, there is a typo in your code: the letter 'e' is missing in the updateValueAndValidity() function. Your code has updat instead of update. Cheers, this was a big help!
  • Link is broken; may be updated to github.com/angular/angular/blob/master/packages/forms/src/… although not quite the same. Could also link to Angular docs
  • Life saver!! The use case that I was stuck was when the user submits a form without touching a single form control. The form is invalid but the controls where not showing any error message
  • this is actually the right answer. If you want single input this.form.controls['name'].markAsTouched();
  • won't work for controls that are already touched, I think..