Angular validation with Required not working

Viewed 37063

Simplest example ever not working. I generated an Angular 4 application using the Angular CLI v1.0.6, changed the content of app.component.html to:

<form #form='ngForm' (ngSubmit)='submitForm(form.value)'>
  <input type='email'
  class='form-control' placeholder='E-mail' name='userEmail' ngModel required >
  <button type='submit'>Submit</button>
</form>

And the content of app.component.ts to:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  submitForm(data){
    console.log(data);
  }
}

I expected the submit function to not be fired in case I didn't supply an email, but it does. What did I miss?

P.S.: I have looked around for examples (e.g.: https://scotch.io/tutorials/angular-2-form-validation), but after many hours I am unable to find a solution, that's why I come to you. I know it is in my face, but somehow I can't see it.

4 Answers

The above answers are right, you just have to add ngNativeValidate to the form tag. I would like to add that if you want the submit button to not perform the (click) action when the form is not valid, use form.checkValidity()

<form ngNativeValidate #form >
   <input type="text" required/>
   <button name="submit"  type="submit" (click)="form.checkValidity()? login() : null">
          Sign In
   </button>
</form>
Related