啥也不说了,先直接上DEMO:

DEMO点我

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!doctype html>
<html ng-app>
<head>
<title>Angular Demo</title>
</head>
<body>
<form action="/test" name="form">
<input ng-model="test" type="text" name="test" required ng-pattern="/^[a-z]+$/">
<span ng-show="form.test.$invalid" style="color:red;">只能是小写的组合</span>
<br>
结果:{{ form.test.$modelValue }}
<br>
<button type="submit" ng-disabled="form.$invalid">提交</button>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</body>
</html>

可以看到没有一行JS,接下来来简单分析一下

1
<html ng-app>

表明这个是一个Angular的APP

1
<form action="/test" name="form">

给这个表单命名为form

1
2
<input ng-model="test" type="text" name="test" required ng-pattern="/^[a-z]+$/">
<span ng-show="form.test.$invalid" style="color:red;">只能是小写的组合</span>

这段html中就是使用了angular内置的一些指令来完成表单的验证,通过required ng-pattern="/^[a-z]+$/"来指名input输入的格式,然后在下面通过ng-show="form.test.$invalid"来对应在验证不通过的时候做出提示。

1
<button type="submit" ng-disabled="form.$invalid">提交</button>

设置当验证不通过时禁用提交按钮

就这样,一行JS都不用写完成表单验证。


浙ICP备2025160166号