使用没有指令的 JavaScript 函数进行 Angularjs 表单/字段验证 [英] Angularjs Form/Field validation using JavaScript function without directives
问题描述
有没有办法在不使用指令的情况下验证一个字段?例如:我想对输入字段进行以下验证.
- 如果字段为空,我们应该显示字段必须包含值"消息.
- 如果字段包含字母数字字符,我们应该显示字段只能包含数字".
- 偶数 - 给用户的消息值必须是偶数".
我想在调用 JavaScript 函数时进行以下验证.
我用谷歌搜索,发现有一种方法可以使用 ng-valid 和 $error ,但是我没有设法让它工作.
下面的代码是根据我得到的答案之一:
<表单名称='theForm' novalidate><input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/><span ng-show='theForm.theText.$error.pattern'>字段只能包含数字</span><span ng-show='theText.length<1'>字段必须包含一个值</span><span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>值必须是偶数</span><br/><input type='submit' value='Submit'/></表单>我想将最后一个 [span] 中的内容放入 JavaScript 函数中,以使其更通用,并最终在条件发生变化时仅更改 JS 而不是 HTML
有人可以请教吗?一个有效的例子会很棒.
解决方案 我很惊讶没有人提到 用户界面验证
$scope.isOdd = function($value){返回 $value % 2;}...<表单名称=我的表单"><输入 ng-model="myVal" name="value" 需要ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input><pre>{{myform.value.$error|json}}</pre></表单>
没有比这更简单的了,它是正确的 AngularJS 验证(不是愚蠢的手表)
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.
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.
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
Can someone please advise? a working example would be great.
解决方案 I'm surprised no one has mentioned 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)
这篇关于使用没有指令的 JavaScript 函数进行 Angularjs 表单/字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文