使用JavaScript功能,无需指令Angularjs表/字段验证 [英] Angularjs Form/Field validation using JavaScript function without directives

查看:106
本文介绍了使用JavaScript功能,无需指令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.


  • 如果字段为空,我们应显示字段必须包含值的消息。

  • 如果字段包含字母数字字符,我们应该表现出场只能包含数字。

  • 偶数 - 消息给用户值必须是偶数

我要让以下到JavaScript函数的调用验证。

我GOOGLE了四周,发现有使用NG-有效和$错误的方式,但是我并没有设法使其工作。

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下面是根据我得到的答案之一:

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>

我要采取什么最后的[跨度]内,为了把一个JavaScript函数中,使之更加通用,并最终改变只有JS,而不是在条件改变HTML

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.

推荐答案

我很惊讶没有人提到 UI的验证

$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>

没有比任何简单,它是PROPER AngularJS验证(不傻手表)

Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)

这里的工作演示

这篇关于使用JavaScript功能,无需指令Angularjs表/字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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