本文介绍了Angular 4支持HTML5验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Angular 4中使用HTML5验证,而不是基于表单的验证/反应验证。我想在浏览器中保持验证运行。

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.

它曾经在Angular 2中工作,但是自从我升级后,我甚至无法获得手动创建的表单而没有任何角度指令来使用HTML5进行验证。

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>


推荐答案

Angular4自动添加无效表单的属性。

Angular4 automatically adds a novalidate attribute to forms.

要覆盖此项,您可以添加 ngNativeValidate 表格的指令。

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

它似乎还添加表单中的ngNoForm ngNativeValidate 具有相同的效果,具体取决于您因某种原因需要声明某些内容而不是表单的用例。

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.

希望这会有所帮助。

这篇关于Angular 4支持HTML5验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:03