AngularJS-加载时触发表单验证 [英] AngularJS - Form validation triggered on load

查看:47
本文介绍了AngularJS-加载时触发表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中添加了字段验证属性,例如"required"和"pattern",该表单位于ng-controller内部.验证有效.但是似乎验证是在页面加载时触发的,并且我看到页面加载时所有字段都被标记为无效并带有错误消息.

I added field validation attributes like "required" and "pattern" in my form, and the form is inside a ng-controller. The validation works. But it seems the validations are triggered on page load, and I see all the fields are marked as invalid with error message when the page load.

我试图按照AngularJS网站上的示例所示,在表单中添加"novalidation"属性,但是没有运气.

I tried to add "novalidation" attribute to the form as indicated in the examples on AngularJS website, but no luck.

我希望在用户第一次尝试与之交互时触发验证.我该怎么办?

I would like to have the validation triggered the first time the user tries to interact with it. How can I do that?

这是一个示例 https://jsfiddle.net/davidshen84/00t197gx/

<div class="mdl-cell mdl-cell-6-col mdl-textfield mdl-js-textfield">
  <input class="mdl-textfield__input" type="text" id="screenname" pattern="[a-zA-Z0-9]{3,}" ng-model="comment.screenname" required/>
  <label class="mdl-textfield__label" for="screenname">Screen Name</label>
</div>

在加载时,您应该看到所有输入字段下方都有一条红线,表明它们处于无效状态.验证后,该行变为蓝色.

On load, you should see all the input fields had a red line under them which indicate they are in the invalid state. And the line turns to blue once validated.

注意:选中按钮上的样式不起作用...不应成为问题的关注点.

Note: The style on the check button does not work...should not be a concern in the problem.

推荐答案

当前实现的(错误的IMHO)是MDL自动验证输入并且不介意验证"表单属性.我必须实现对空输入值的检查(跳过验证并删除is-invalid类),并且由于角度形式验证需要"novalidate"属性,因此请检查:

What is currently implemented (wrong IMHO) is that MDL automatically validates input and doesn't mind "novalidate" form attribute. I had to implement check for empty input value (skip validation and remove is-invalid class) and, since angular form validation requires "novalidate" attribute, check:

if(input.form.novalidate = true)//跳过验证

那样,您实际上可以关闭MDL验证,并保留所有内容.实际上还需要做一件事.您可以创建用于验证表达式的angular指令,并在必要时添加is-invalid类:

that way you can actually turn off mdl validation and leave everything to angular. One more thing is actually required. You can create angular directive which validates expression and add is-invalid class if necessary:

div class ="mdl-textfield" mdl-validator ="form.email.$ error"

这篇关于AngularJS-加载时触发表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆