简体   繁体   English

如何在AngularJS的输入字段中捕获模式错误?

[英]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) . 我建立了一个函数捕获错误,但它仅适用于标准HTML5验证,如果我使用ng-pattern则无法捕获错误:(怎么做?可能类似于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: 您可以在以下条件下使用error.pattern ,例如以下代码:

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 . 观察: ngPattern和其他验证器一样,将为模式验证器ng-invalid-pattern添加ng-invalid和特定的类。 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. 通过模式验证时, $scope.formName.ControlName.$error.pattern将是未定义的,否则将有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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