且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用不带指令的 JavaScript 函数进行 Angularjs 表单/字段验证

更新时间:2023-02-15 14:35:52

我很惊讶没有人提到 用户界面验证

$scope.isOdd = function($value){返回 $value % 2;}...<表单名称="myform"><input 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)

Here's a working demo

相关阅读

技术问答最新文章