ng-messages AngularJs 表单校验方式
最新研究了一下表单校验,直接上代码。
<!DOCTYPE html>
<html ng-app='app'>
<head>
<meta charset="utf-8">
<title translate="TITLE">Basic usage</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<style>body { text-align: center;
padding-top: 30px;
}
</style>
<script type="text/ng-template" >
angular.module('app', ['ngMessages'])
.controller('FormCtrl', function($scope) {
})
.directive('matchValidator', function() {
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
ngModel.$setValidity('match', value == scope.$eval(attrs.matchValidator));
return value;
});
}
}
})
.directive('passwordCharactersValidator', function() {
var PASSWORD_FORMATS = [
/[^ws]+/, //special characters
/[A-Z]+/, //uppercase letters
/w+/, //other letters
/d+/ //numbers
];
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
var status = true;
angular.forEach(PASSWORD_FORMATS, function(regex) {
status = status && regex.test(value);
});
ngModel.$setValidity('password-characters', status);
return value;
});
}
}
})
</script>
</head>
<body >
<!-- ng-controller="FormCtrl" ng-submit="submit()" ng-if="interacted(my_form.password)"-->
<form name="my_form" class="main-form container" ng-controller="FormCtrl" novalidate>
<div class="control-group">
<label for="input_password">Create a password:</label>
<input class="form-control"
type="password"
name="password"
>This password does not match the password entered before</div>
</div>
</div>
</form>
</body>
</html>
运行结果: