代码:
<h1>Validation Example</h1>
<form class="form-horizontal container" ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<div class="form-group">
<label class="control-label">用户名:</label>
<input class="form-control" name="user" type="text" ng-model="user" required />
<span class="text-danger" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">用户名是必须的</span>
</span>
</div>
<div class="form-group">
<label class="control-label">邮箱:</label>
<input class="form-control" name="email" type="email" ng-model="email" required />
<span class="text-danger" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">邮箱是必须的</span>
<span ng-show="myForm.email.$error.email">邮箱格式不正确</span>
</span>
</div>
<p>
<button class="btn btn-success" ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty&&myForm.email.$invalid">
确定提交
</button>
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function ($scope) {
$scope.user = 'admin';
$scope.email = "100@qq.com";
});
</script>
结果:
说明:
1.客户端的验证不能确保用户输入数据的安全,所以服务端的数据验证也是必须的。
2.HTML 表单属性 novalidate 用于禁用浏览器默认的验证。
实例解析
AngularJS ng-model 指令用于绑定输入元素到模型中。
模型对象有两个属性: user 和 email。
我们使用了 ng-show指令, color:red 在邮件是 $dirty 或 $invalid 才显示。
属性 | 描述 |
---|---|
$dirty | 表单有填写记录 |
$valid | 字段内容合法的 |
$invalid | 字段内容是非法的 |
$pristine | 表单没有填写记录 |
二、为表单验证状态添加自定义样式:
/*交互且必填样式*/
form.validate .ng-invalid-required.ng-dirty {
background-color: orange;
}
/*交互不合法样式*/
form .ng-invalid.ng-dirty {
background-color: lightpink;
}
/*邮件不合法且交互过*/
form.validate .ng-invalid-email.ng-dirty {
background-color: lightgoldenrodyellow;
}
.error {
color: red;
font-weight: bold;
}
/*不为空的验证通过*/
form .ng-not-empty.ng-valid {
/*color: green;
font-weight: bold;*/
border: 1px solid green;
}
更多: