javascript 在 angularjs 表单验证中强制 ng-dirty
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18324773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force ng-dirty in angularjs form validation
提问by Fernando
Doing form validation with angularjs I want to mark all required fields as erroneous when the user click submit.
使用 angularjs 进行表单验证我想在用户单击提交时将所有必填字段标记为错误。
I am using input.ng-dirty.ng-invalid to style the controls with error. So what I want is to set ng-dirty on required controls (or all controls.. it will be the same for me) when the user submits the form.
我正在使用 input.ng-dirty.ng-invalid 来设置带有错误的控件的样式。所以我想要的是在用户提交表单时在所需的控件(或所有控件..对我来说都是一样的)上设置 ng-dirty 。
Validation is working. I understand why, what I am trying could be wrong, but I found no other way to do the same effect, except something that I think is too complicated to be right.
验证工作。我明白为什么,我正在尝试的可能是错误的,但我发现没有其他方法可以达到相同的效果,除了我认为太复杂而不正确的方法。
What I tried was:
我尝试的是:
<div ng-app>
<form novalidate>
<input name="formvalue" type="text" ng-model="formvalue" required />
<input type="submit" />
</form>
</div>
回答by Matthew.Lothian
Let's start by adding angular to your jsfiddle by wrapping it in
让我们首先将 angular 添加到您的 jsfiddle 中
<div ng-app>...</div>
By default the required field will be validated on input (dirty). If you want to have them validated on submit before any input (pristine), then you can run a function on your submit button that will check for pristine fields and dirty them.
默认情况下,必填字段将在输入(脏)时进行验证。如果您希望在任何输入(原始)之前在提交时验证它们,那么您可以在提交按钮上运行一个函数,该函数将检查原始字段并弄脏它们。
That is what i have done in the example: http://jsfiddle.net/yq4NG/6/
这就是我在示例中所做的:http: //jsfiddle.net/yq4NG/6/
You could probably build a reusable solution using custom formatters and validators but this is a simple on off solution.
您可能可以使用自定义格式化程序和验证程序构建一个可重用的解决方案,但这是一个简单的开关解决方案。
EDIT:
编辑:
Simpler again using just classes: http://jsfiddle.net/yq4NG/8/
再次使用类更简单:http: //jsfiddle.net/yq4NG/8/
EDIT [as suggested by @XMLilley in the comments]:
编辑 [正如@XMLilley 在评论中所建议的]:
Because angular doesn't provide a $setDirty()
method that's equivalent to $setPristine()
we're triggering the $dirty
state by simply updating the $viewValue with the contents of the $modelValue
. It changes nothing, but simulates a user having manually entered each $pristine
field and messed around with the value without changing anything.
因为 angular 没有提供一种$setDirty()
方法,相当于$setPristine()
我们$dirty
通过简单地用$modelValue
. 它什么都不改变,但模拟用户手动输入每个$pristine
字段并在不更改任何内容的情况下弄乱值。