0
votes

I have created a reactive form in angular. I am able to get the validation of the control on its touch, But not getting validated on the submission of the form by click on the submit button. My code is as like below :

<form [formGroup]="myform" (ngSubmit)="SubmitDetails()">
  <div class="row">
      <label for="name">Name:</label>

  <input type="text" id="Name" name="Name" formControlName="Name"/>
  <span *ngIf="myform.controls.Name.invalid && myform.controls.Name.touched">Please Enter Name.</span>

  </div>
<br/>
<div class="row">
    <label for="age">Age:</label>
  <input type="text" id="Age" name="Age" formControlName="Age"/>
<span *ngIf=" myform.controls.Age.invalid && myform.controls.Age.touched">Please Enter Age.</span>
</div><br/>

  <button type="submit">Submit</button>
</form>

2
Try with <button type="submit" (click)="SubmitDetails()">Submit</button> - Emilien
I dont think so to write inn funnction & validate all the things. It whould validate on submit. I had seen a property how "touched" exists. Can I get with any other property like submitted in directive ? - Srikanth Reddy
What do you want exactly ? - Emilien
Try this : myform.controls.Name.invalid && (myform.controls.Name.touched || myForm.submitted) - Arcteezy
on form submission I should get the reuired field messages like how I get on immediate touched of the control with the line "myform.controls.Age.touched". - Srikanth Reddy

2 Answers

0
votes

You can check if your form is valid with property vaild of formGroup:

this.yourFormGroup.valid;

On your submit function, just check if form is valid, if yes, then continue, else mark the form as dirty or touched:

submitFunction() {
  if(this.yourFormGroup.valid) {
    console.log('it s ok!');
  }else {
    this.yourFormGroup.markAsDirty();
}

Edit: I have a doubt about using markAsDirty on the formGroup, if it doesnt work, just simply loop all formControl from the formGroup, and mark them as dirty():

this.yourFormGroup.get('yourFormControl').markAsDirty();
0
votes

You could add a disabled state to your button if the form is not valid. Not sure if this works with your UI/UX approach but worth mentioning.

<button type="submit" [disabled]="form.invalid">Submit</button>