简体   繁体   中英

How to catch pattern error in input field in AngularJS?

I built a function catch error but it works correctly only for standard HTML5 validation,if i use ng-pattern it cannot catch the error:( How can it be made? Maybe something like if(error.login$invalid) .

Template:

<input type="text" name="login" class="form-input"
    ng-model="newUser.login"
    ng-pattern="loginPattern"
    required>
<div class="error"
    ng-show="registrationForm.login.$invalid && registrationForm.login.$dirty">
    {{getSigningError(registrationForm.login.$error)}}
</div>

Controller:

$scope.getSigningError = function(error){
    if(angular.isDefined(error)){
        if(error.required){
            return "Field shouln`t be empty"
        }
        if(error.email){
            return "Enter correct email"
        }
        if(error.login){
            return "Enter correct login"
        }
    }
}

You can use error.pattern on your conditions like the code bellow:

if(error.pattern){
    return "Enter the correct format"
}

Or you can handle it from the template side using this:

<span ng-if="myForm.login.$error.pattern">Invalid Pattern</span>

Observation: ngPattern , like other validators, will add the ng-invalid and the specific class for the pattern validator ng-invalid-pattern . So if you want to apply specific styles for this kind of errors you can use this class.

.ng-invalid-pattern  {
    color: yellow;
}

Refs

Forms

If you aren't passing error, you can check like your controller:

if ($scope.formName.ControlName.$error.pattern) {}

$scope.formName.ControlName.$error.pattern will be undefined when pattern validation passed and valid otherwise.

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