嘿,我正试图找出我的代码有什么问题。该代码应该验证密码,要求具有很少的特殊字符并设置其最小长度。
我让它设置正确的长度,但我似乎无法使指令文件正常工作。
app.directive('myPassord',function()
{
return{
require:'ngModel',
link:function(scope,element,attr,myFormCtrl){
function myValidation(value)
{
if (value.indexOf("$") > -1 || value.indexOf("%") > -1 || value.indexOf("^") > -1 || value.indexOf("&") > -1 || value.indexOf("*") > -1){
myCtrl.$setValidity('Charactervalidator', false);
}else{
myCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
html文件
<div ng-controller = "myFormCtrl" class="form-group">
<form name ="Form1" novalidate="novalidate" class="Form1">
<p>
<label for = "password1" class= "col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength ="8" required data-my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red"> Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
答案 0 :(得分:2)
我更正你的代码。试试这个代码。希望这可以帮助你
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div class="form-group">
<form name="Form1" novalidate="novalidate" class="Form1">
<p>
<label for="password1" class="col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength="8" required my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red">
Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
<h1>{{myForm.myInput.$valid}}</h1>
<script>
var app = angular.module('myApp', []);
app.directive('myPassword', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, myFormCtrl) {
function myValidation(value) {
if (value.indexOf("$") > -1 ||
value.indexOf("%") > -1 ||
value.indexOf("^") > -1 ||
value.indexOf("&") > -1 ||
value.indexOf("*") > -1) {
myFormCtrl.$setValidity('Charactervalidator', true);
} else {
myFormCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
</script>
</body>
</html>
&#13;