简体   繁体   中英

Validating password with AngularJS

Hey I'm trying to figure out what is wrong with my code. The code is supposed to validate password with the requirement of having few special characters and setting its minimum length.

I got it to set on the right length but I can't seem to get the directive file working.

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);
        }

    }
});

The html file

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

I correct your code. Try this code. Hope this helps you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM