【问题标题】:Using AngularJS custom field validation使用 AngularJS 自定义字段验证
【发布时间】:2014-11-20 13:02:15
【问题描述】:

我正在使用$asyncValidators 来验证字段,但希望它仅在字段失去焦点时触发,而不是在每次更改时触发。这是可能的还是我必须使用$asyncValidators以外的其他东西? 使用$asyncValidators的代码示例(取自documentation

ngModel.$asyncValidators.uniqueUsername = function (modelValue, viewValue) {
    var value = modelValue || viewValue;

    // Lookup user by username
    return $http.get('/api/users/' + value).
        then(function resolved() {
            //username exists, this means validation fails
            return $q.reject('exists');
        }, function rejected() {
            //username does not exist, therefore this validation passes
            return true;
        });
};

【问题讨论】:

    标签: javascript angularjs validation angularjs-directive


    【解决方案1】:

    我认为您可以使用 ngModelOptions 指令来实现。

    ng-model-options="{ updateOn: 'blur' }"
    

    您可以强制您的模型仅针对某些预定义事件进行“评估”。 在你的情况下,你想在离开现场时评估它,所以在 blur 事件上。

    Official documentation of ngModelOptions directive

    【讨论】:

    • 是的,它有效!也许我应该更仔细地阅读文档:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2020-08-24
    • 2019-10-04
    • 2013-05-24
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多