Angular 2 Reactive Forms trigger validation on submit

angular 4 form validation on submit example
angular material form validation on submit
custom validation in angular 6 reactive form
angular reactive form submit
angular 9 form validation
angular template form validation
reactive form dirty
angular 6 form validation on button click

is there a way that all validators of a reactive forms can be triggered upon submit and not only by the "dirty" and "touch" events?

The reason for this is we have a very large forms which doesn't indicate if a field is required or not, and user might miss some of the required control, so upon submit, it is expected that all of the invalid fields which are missed by the end user will be shown.

I have tried marking the form as "touched" by using the

FormGroup.markAsTouched(true);

it worked, and so I also tried marking it as "dirty"

FormGroup.markAsDirty(true);

but the css of the class is still "ng-pristine",

Is there a way to trigger it manually from the component, I tried googling it to no avail, thanks you in advance!

UPDATE

I already got it working by iterating the FormGroup.controls and marking it as "dirty", but is there a "standard" way to do this.


This can be achieved with the sample presented here, where you can make use of NgForm directive:

<form [formGroup]="heroForm" #formDir="ngForm">

and then in your validation messages just check if the form is submitted:

<small *ngIf="heroForm.hasError('required', 'formCtrlName') && formDir.submitted">
  Required!
</small>

EDIT: Now is also { updateOn: 'submit'} provided, but that works only if you do not have required on the form, as required is displayed initially anyway. But to display that functionality:

// fb is 'FormBuilder'
this.heroForm = this.fb.group({
 // ...
}, { updateOn: 'submit'})

Angular 2 Reactive Forms trigger validation on submit, is there a way that all validators of a reactive forms can be triggered upon submit and not only by the "dirty" and "touch" events? The reason for this is we have a  When working with forms we have 2 options: the first one is to disable the submit button if the form is invalid (meaning there is at least one invalid field) and the second option is to validate the form before the HTTP POST action is executed by the code and display a message to the user to fix any pending validation errors.


There are multiple ways to solve the problem. The @Splaktar's answer won't work if you have nested formgroups. So, here's the solution which will work with nested form groups.

Solution 1: Iterate through all formgroups and formcontrols and programmatically touch them to trigger validations.

Template code:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
...
<button type="submit" class="btn btn-success">Save</button>
</form>

component.ts code:

    onSubmit() {
        if (this.myForm.valid) {
            // save data
        } else {
            this.validateAllFields(this.myForm); 
        }
    }

validateAllFields(formGroup: FormGroup) {         
        Object.keys(formGroup.controls).forEach(field => {  
            const control = formGroup.get(field);            
            if (control instanceof FormControl) {             
                control.markAsTouched({ onlySelf: true });
            } else if (control instanceof FormGroup) {        
                this.validateAllFields(control);  
            }
        });
    }

Solution 2: Use a variable to check if the form has been submitted or not. FYI: The submitted field for the ngForm is currently being tested and will be included in future Angular versions. So there will not be a need to create your own variable.

component.ts code

private formSubmitAttempt: boolean;

onSubmit() {
        this.formSubmitAttempt = true;
        if (this.myForm.valid) {
            console.log('form submitted');
        }
   }

Template code:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <div class="form-group">
        <label class="center-block">
            Name:
            <input class="form-control" formControlName="name">
        </label>
        <div class="alert alert-danger" *ngIf="myForm.get('name').hasError('required') && formSubmitAttempt">
            Name is required
        </div>
        ...
</form>

Angular 2 Reactive Forms trigger validation on submit, A good example is a publishing workflow, where you have a saveDraft() that is your actual submit-with handler, but in your publish() function,  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.


Coming back after some months, I share here the improved version based on all the comments, just for the record:

markAsTouched(group: FormGroup | FormArray) {
  group.markAsTouched({ onlySelf: true });

  Object.keys(group.controls).map((field) => {
    const control = group.get(field);
    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {
      this.markAsTouched(control);
    }
  });
}

Hope it will be useful!

UPDATE: Angular 8 introduced FormGroup.markAllAsTouched() and it does this! :D

Manually trigger validation · Issue #30 · bvaughn/angular-form-for , I've setup the form to validate on submit rather than as soon as each field is changed, this is implemented with a 'submitted' field in the app  Validating Reactive Forms in Angular. Forms are a fundamental part of every angular application. One of the greatest features of forms is, that you can validate the input of the user before it is send to the server. In this tutorial you are going to learn how you can validate your angular reactive forms.


This can be accomplished via markAsTouched(). Until PR #26812 is merged, you can use

function markAllAsTouched(group: AbstractControl) {
  group.markAsTouched({onlySelf: true});
  group._forEachChild((control: AbstractControl) => markAllAsTouched(control));
}

You can find out more in the source code.

Angular 6, We also call the form's updateValueAndValidity() method, as we need to recalculate the value and validation status of the form. If you choose this  Important: if using Angular material form controls + reactive forms. Call onSubmit(undefined) to properly set submitted = true on the [formGroup] directive. Note: The directive is not the same object as the angular form itself (more below on that) Here's part of the sourcecode for the [formGroup] directive. (for reactive forms)


I found something that might be of interest:

On submit I set the submitAttempt = true and put this in the div where validation should take place:

nickname.touched || nickname.dirty || (nickname.untouched && submitAttempt)

meaning: If it hasn't been touched, and we tried to submit, the error shows.

Three Ways to Dynamically Alter your Form Validation in Angular, updateOn: 'blur' and updateOn: 'submit' are the options we were really craving for while working with Angular Forms. Now it's available out of  In Angular 5, two new form validation techniques are introduced. Considering that you are familiar with FormBuilder, FormGroup, FormControl, Validators and etc. I’ll just jump into some examples. To, give you a heads up, here is how our form model looks like, Notice that the changes are immediately reflected in the form model and the


Angular Form Validation on Blur and Submit, This page shows how to validate user input in the UI and display useful validation messages using both reactive and template-driven forms. It assumes some  Validating input in reactive formslink. 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.


Form validation, Imagine that you have a form with a checkbox and an email field. onSubmit() method. angular-conditional-validators-2-naive - StackBlitz value changes of the checkbox and manually trigger validation of the email field:  Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms. Reactive Forms live-example / download example.


Angular trigger validation manually, And that is it! Angular-cli will automatically bootstrap the project in a folder named angular-reactive-validation. Creating The Angular Reactive Form. We will be using the existing app.component.ts file for our component logic; feel free to use anywhere you deem fit in your application. Creating the form group.