Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 enable HTML5 validation

Tags:

html

angular

I want to use HTML5 validation in Angular 4 rather than their form's based validation/reactive validation. I want to keep the validation running in the browser.

It used to work in Angular 2, but since I've upgraded, I can't get even manually created forms without any angular directives to validate using HTML5.

For instance, this won't validate in the browser at all:

<form> <h2>Phone Number Validation</h2> <label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br /> <input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>  <input type="submit" value="Submit">  </form> 
like image 487
Magn3s1um Avatar asked Apr 03 '17 16:04

Magn3s1um


People also ask

Is HTML5 validation accessible?

Short Answer. Yes the standard HTML5 validation is accessible and will pass WCAG2. 1 AA, but you can do a lot better with some JavaScript.

Which HTML5 attribute is used for data validation?

The pattern attribute of the <input> element allows you to add basic data validation without resorting to JavaScript. It works by matching the input value against a regular expression.

How do I validate a form in HTML?

To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.


2 Answers

Angular4 automatically adds a novalidate attribute to forms.

enter image description here

To override this, you can add the ngNativeValidate directive to the form.

<form ngNativeValidate> <h2>Phone Number Validation</h2> <label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br /> <input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>  <input type="submit" value="Submit">  </form> 

Unfortunately I do not see this reflected in the docs yet, but found it by looking at the source code: https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_no_validate_directive.ts

It appears also adding ngNoForm to the form has the same effect as ngNativeValidate depending on your use-cases for needing to declare something as not a form for whatever reason.

Hope this helps.

like image 58
Tyler Jennings Avatar answered Oct 07 '22 07:10

Tyler Jennings


use ngNoForm or ngNativeValidate in your form

<form ngNoForm/ngNativeValidate> ... </form> 
like image 43
Simran Avatar answered Oct 07 '22 06:10

Simran