Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation of password using ng-pattern

I want to validate password using ng-pattern. I use the same regular expression in my model and it works. I want to display error message if password is not valid (at least 7 characters, one of them must be number).

I've added regular expression to ng-pattern, but it only shows error message, if password is shorter than 7 characters (because I use ng-minlength), and it doesn't show, if password is also in bad format. Can someone help me to figure out why it happens?

Model:

    [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}$", ErrorMessage = "Máte příliš krátké heslo (minimum je 7 znaků), popř. vaše heslo není ve správném tvaru.")]
    [Required(ErrorMessage = "Zadejte prosím Vaše heslo.", AllowEmptyStrings = false)]
    public string Password { get; set; }

Registration.cshtml:

    <input type="password" style="width: 600px" class="form-control" name="Password" id="Password" ng-pattern="^(?=.*[a-z])(? =.*[A-Z])(? =.*\d)[a-zA-Z\d]{7,}$" ng-model="User.Password" ng-minlength="7" ng-class="submitted?'ng-dirty':''" required />
                    <span class="error" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.required">Zadejte prosím Vaše heslo.</span>
                    <span class="error" ng-show=" (form.Password.$dirty || submitted) && (form.Password.$error.minlength || form.Password.$error.pattern)">Máte příliš krátké heslo (minimum je 7 znaků), popř. vaše heslo není ve správném tvaru.</span>
                    <span class="success" ng-show=" (form.Password.$dirty || submitted) && form.Password.$valid">Vaše heslo má dostatečnou délku a je ve správném tvaru.</span>
like image 553
mates.lukas94 Avatar asked Mar 11 '23 12:03

mates.lukas94


2 Answers

You will have to use / before and after your regex, and as pointed out by @MikeMcCaughan, remove any spaces in the positive lookahead. For example, change (? = to (?=

ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}$/"
like image 125
Ibrahim Avatar answered Mar 19 '23 19:03

Ibrahim


Change pattern to /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$/

<input type="password" style="width: 600px" class="form-control" name="Password" id="Password" ng-pattern="/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$/" ng-model="User.Password" ng-minlength="7" ng-class="submitted?'ng-dirty':''" required />
                <br/>
                <span class="error" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.required">Required</span>
                <span class="error" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.minlength">Mini 7 characters</span>
                <span class="success" ng-show=" (form.Password.$dirty || submitted) && form.Password.$error.pattern">Invalid</span>

Have a look at demo link https://plnkr.co/edit/Xo1qfEHS2NrdUHyHDjml?p=preview

like image 31
Naghaveer R Avatar answered Mar 19 '23 20:03

Naghaveer R