Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 "required" attribute is not checked on form submit

Tags:

html

angular

My very basic Angular 4 form doesn't validate the input (text) fields with the "required" attribute. Input with "required" attribute should be validated by the browser like the html 5 default behaviour without Angular. Was there any change in Angular 4? The same code worked fine with Angular 2.

<form (ngSubmit)="onSubmit()" #testForm="ngForm">
  <input type="text" id="test1" name="test1" [(ngModel)]="test" required>
  <input type="text" id="test2" name="test2" [(ngModel)]="test" [required]="true">
  <input type="text" id="test3" name="test3" [(ngModel)]="test" [attr.required]="true">
  <button type="submit">submit</button>
</form>

Try in this plunkr: http://plnkr.co/edit/Wow7NUhaC0KjHtOfVQ2c?p=preview

like image 545
Simon Avatar asked Feb 06 '26 19:02

Simon


1 Answers

I found it by myself...

There was a change from Angular 2 to 4. Under Angular 4 I have to set the "ngNativeValidate", which was default behaviour under Angular 2.

This will work with the default html5 validator "required":

<form (ngSubmit)="onSubmit()" #testForm="ngForm" ngNativeValidate>
  <input type="text" id="test1" name="test1" [(ngModel)]="test" required>
  <input type="text" id="test2" name="test2" [(ngModel)]="test" [required]="true">
  <input type="text" id="test3" name="test3" [(ngModel)]="test" [attr.required]="true">
  <button type="submit">submit</button>
</form>

Corrected Plunkr Someones reported Angular issue which pointed me to the failure

like image 199
Simon Avatar answered Feb 12 '26 14:02

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!