Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

html - Angular 4 enable HTML5 validation

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...