力纳克脏的angularjs表单验证 [英] Force ng-dirty in angularjs form validation

查看:105
本文介绍了力纳克脏的angularjs表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做表单验证与angularjs我要标记所有必填字段为错误,当用户点击提交。

Doing form validation with angularjs I want to mark all required fields as erroneous when the user click submit.

我使用input.ng-dirty.ng-无效,错误样式的控制。所以,我要的是设定NG脏所需的控制(或所有控件..这将是我一样),当用户提交表单。

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.

验证工作。我明白为什么,我试图可能是错的,但我没有发现其他的方式做同样的效果,但我觉得太复杂是正确的东西。

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.

我试过是:

<div ng-app>
    <form novalidate>
        <input name="formvalue" type="text" ng-model="formvalue" required />
        <input type="submit" />
    </form>
</div>

http://jsfiddle.net/yq4NG/

推荐答案

让我们开始通过添加角到您的jsfiddle在它包装

Let's start by adding angular to your jsfiddle by wrapping it in

<div ng-app>...</div>

http://jsfiddle.net/yq4NG/1/

默认情况下,所需的字段将在输入(脏)验证。如果你想他们已经验证的任何输入(原始)之前递交,那么你就可以在你的提交按钮,将检查原始的领域和肮脏的他们跑的功能。

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.

这是我在这个例子做了​​: http://jsfiddle.net/yq4NG/6/

That is what i have done in the example: 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.

编辑:

再简单只用类: http://jsfiddle.net/yq4NG/8/

EDIT [由@XMLilley的意见建议]:

EDIT [as suggested by @XMLilley in the comments]:

由于角不提供$使用setDirty()方法,这相当于$ setPristine()我们通过简单的使用$ modelValue的内容更新$ viewValue触发$脏状态。它改变了什么,但模拟用户具有手动输入每个$原始字段的值为搞砸周围没有任何改变。

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.

这篇关于力纳克脏的angularjs表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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