2

I am new to Angular. I have read this, this and this question thoroughly, But none of them are of my use as they are using jquery. My form is pretty basic registration form with only 4 basic fields. Username, password, confirm password and zipcode and a submit button. To keep this post clean and there are multiple files involved I've uploaded necessary files on github.

  1. app.component.html
  2. app.component.ts
  3. app.module.ts

And I am handling validators for password and zipcode separately in

  1. validator.ts

Validations are working perfectly fine. But the problem is that the form still gets submitted even when there are validation issues on frontend. Here is my screenshot. Please suggest me a solution or at least give some hint.

PS: I am following this youtube tutorial.

enter image description here

1 Answer 1

3

First, disable the button

<button type="submit" class="btn btn-primary" (click)="onSubmit()" [disabled]="!form.valid">Submit</button>

Next, use a condition before submit.

  onSubmit(){
    if (!this.form.valid) return;

    // console.log(this.form.controls.zip);
    this.form.markAsTouched();
    console.log(this.form.value);

  }

Finally, add that attribute to your form :

<form [formGroup]="form" novalidate>
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for adding a programmatic validation. I have seen it too often that people simply rely on disabling the button.
@ak.leimrey did you punch them in the throat ? I would have :D
I accept this wholeheartedly. I'm so embarrassed I cant even figure out small problems. :-( Thank you @Maryannah.
@Maryannah I wish. Then again, it makes me feel so smart that I didn't do that and I need every bit of validation, given my limited skillset!
@Maryannah. Yes Sir. Always.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.