Is there a way to validate a field in angular without using a directive? For example: I want to make following validation on an input field.
有没有一种方法可以在不使用指令的情况下验证一个角的场?例如:我想对输入字段进行以下验证。
- If field is empty we should show "Field must contain a value" message.
- 如果字段为空,我们应该显示“字段必须包含值”消息。
- if field contains alpha Numeric characters we should show "Field can contain only digits".
- 如果字段包含字母数字字符,我们应该显示“字段只能包含数字”。
- An EVEN number - message to the user "Value must be an even number".
- 向用户发送的偶数消息“值必须是偶数”。
I want to make following validation in a call to JavaScript function.
我想在调用JavaScript函数时进行以下验证。
I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.
我在谷歌上搜索了一下,发现有一种方法可以使用ng-valid和$error,但是我并没有设法让它正常工作。
Code below is according to one of the answers I got:
下面的代码是根据我得到的一个答案:
<div ng-app>
<form name='theForm' novalidate>
<input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
<span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
<span ng-show='theText.length<1'>Field must contain a value</span>
<span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
<br/><input type='submit' value='Submit' />
</form>
I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing
我想把最后一个[span]中的内容放到一个JavaScript函数中,以便使它更通用,最终在条件变化时只修改JS而不修改HTML
Can someone please advise? a working example would be great.
有人可以请告知?一个有用的例子会很棒。
4 个解决方案
#1
21
I'm surprised no one has mentioned ui-validate
我很惊讶没有人提到ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
没有比这更简单的了,它是合适的AngularJS验证(不是傻手表)
这是一个演示工作
#2
3
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
看看angularjs表单文档——http://docs.angularjs.org/guide/forms。一般来说,它基于HTML5属性,如required, min, max等。
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
例如,要完成您的第一个需求——“一个空字段应该显示“字段必须包含一个值”消息,yo uwould会这样做:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern
attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
对于只有数字的字段,您可以使用模式属性和匹配的正则表达式(例如:http://www.wufoo.com/html5/attributes/10-pattern.html)。
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern
attribute somehow.
即使是数字验证,我也不确定——我认为您必须为此使用自定义验证(意味着您必须创建一个指令)或者以某种方式使用pattern属性。
Last but not least - remember to add novalidate
to the <form>
tag. Otherwise the browser will try to validate your fields as well and you don't want that:
最后但并非最不重要——请记住将novalidate添加到
<form ... novalidate>
...
</form>
#3
3
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
我知道这个问题由来已久,我也知道你不想要一个指令,但如果它是“有角的”方式,你可以考虑使用一个指令……这是我的角度验证。我在Github上做了一个项目,我认为它和任何可用的东西相比都是石头……我以优秀的Laravel PHP框架为基础,使它在角度下可用……它是如此的简单,你需要2行代码,1行输入,1行显示错误,就是这样…永远不要再多也不要少!!!说得够多了,让我们举几个例子:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer"
and the error message will always display in the next <span>
Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur
and onkeyup
. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000"
to make a 5 sec. timeout. Full example:
所以我可以定义任意数量的验证规则(已经有25个以上类型的验证器),我想在一个简单的指令验证="min_len:2|max_len:10|需要|integer"中显示错误消息,你们不喜欢它吗?输入一行代码,错误显示一行代码,再简单不过了……哦,如果你想添加的话,我甚至支持你的自定义Regex。另外,我还支持你想要的任何触发事件,最常见的可能是onblur和onkeyup。Oh和我还通过JSON外部文件支持多种本地化语言。我真的把我想要的所有功能都加到了一个疯狂的简单指令中。当您只需要2行代码时,就不再需要10行代码的集群形式(抱歉,但总是会发现有点极端),即使是5个验证器的输入也不需要2行代码。不用担心它不会变成无效的,我也处理过了,它都处理好了"角"的方法。看看我的Github项目Angular-Validation…我肯定你会喜欢的=)更新另一个糖果奖金!为了使用户体验更加流畅,我在timer上添加了验证。概念很简单,在用户输入时不要打扰他,但如果他暂停或更改输入(onBlur),请进行验证……爱它! ! !您甚至可以根据自己的喜好来定制计时器,我已经决定在指令中将其默认为1秒,但是如果您想要自定义,您可以调用as,例如,类型限制="5000"来进行5秒超时。完整的例子:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
更新#2还增加了输入匹配确认(例如:密码确认),这是一个示例代码
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span>
to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
更新#3重构了指令,这样就没有必要使用来显示错误的要求了,指令现在自己处理它,看到代码变化在顶部反射。演示在柱塞上增加了一个实时演示
#4
2
Well you can try to create a func
你可以尝试创造一个有趣的东西
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
该方法可以在当前控制器范围或$rootScope上定义。
Not a very angular way, as directives would be better but i think it would work.
这不是一种很有棱角的方式,因为指示会更好,但我认为它会起作用。
#1
21
I'm surprised no one has mentioned ui-validate
我很惊讶没有人提到ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
没有比这更简单的了,它是合适的AngularJS验证(不是傻手表)
这是一个演示工作
#2
3
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
看看angularjs表单文档——http://docs.angularjs.org/guide/forms。一般来说,它基于HTML5属性,如required, min, max等。
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
例如,要完成您的第一个需求——“一个空字段应该显示“字段必须包含一个值”消息,yo uwould会这样做:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern
attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
对于只有数字的字段,您可以使用模式属性和匹配的正则表达式(例如:http://www.wufoo.com/html5/attributes/10-pattern.html)。
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern
attribute somehow.
即使是数字验证,我也不确定——我认为您必须为此使用自定义验证(意味着您必须创建一个指令)或者以某种方式使用pattern属性。
Last but not least - remember to add novalidate
to the <form>
tag. Otherwise the browser will try to validate your fields as well and you don't want that:
最后但并非最不重要——请记住将novalidate添加到
<form ... novalidate>
...
</form>
#3
3
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
我知道这个问题由来已久,我也知道你不想要一个指令,但如果它是“有角的”方式,你可以考虑使用一个指令……这是我的角度验证。我在Github上做了一个项目,我认为它和任何可用的东西相比都是石头……我以优秀的Laravel PHP框架为基础,使它在角度下可用……它是如此的简单,你需要2行代码,1行输入,1行显示错误,就是这样…永远不要再多也不要少!!!说得够多了,让我们举几个例子:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer"
and the error message will always display in the next <span>
Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur
and onkeyup
. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000"
to make a 5 sec. timeout. Full example:
所以我可以定义任意数量的验证规则(已经有25个以上类型的验证器),我想在一个简单的指令验证="min_len:2|max_len:10|需要|integer"中显示错误消息,你们不喜欢它吗?输入一行代码,错误显示一行代码,再简单不过了……哦,如果你想添加的话,我甚至支持你的自定义Regex。另外,我还支持你想要的任何触发事件,最常见的可能是onblur和onkeyup。Oh和我还通过JSON外部文件支持多种本地化语言。我真的把我想要的所有功能都加到了一个疯狂的简单指令中。当您只需要2行代码时,就不再需要10行代码的集群形式(抱歉,但总是会发现有点极端),即使是5个验证器的输入也不需要2行代码。不用担心它不会变成无效的,我也处理过了,它都处理好了"角"的方法。看看我的Github项目Angular-Validation…我肯定你会喜欢的=)更新另一个糖果奖金!为了使用户体验更加流畅,我在timer上添加了验证。概念很简单,在用户输入时不要打扰他,但如果他暂停或更改输入(onBlur),请进行验证……爱它! ! !您甚至可以根据自己的喜好来定制计时器,我已经决定在指令中将其默认为1秒,但是如果您想要自定义,您可以调用as,例如,类型限制="5000"来进行5秒超时。完整的例子:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
更新#2还增加了输入匹配确认(例如:密码确认),这是一个示例代码
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span>
to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
更新#3重构了指令,这样就没有必要使用来显示错误的要求了,指令现在自己处理它,看到代码变化在顶部反射。演示在柱塞上增加了一个实时演示
#4
2
Well you can try to create a func
你可以尝试创造一个有趣的东西
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
该方法可以在当前控制器范围或$rootScope上定义。
Not a very angular way, as directives would be better but i think it would work.
这不是一种很有棱角的方式,因为指示会更好,但我认为它会起作用。