如何在模糊点火时限制对场的验证?

时间:2014-07-14 13:47:57

标签: javascript angularjs validation angularjs-directive

以下代码正确地对文本字段(时间格式00:00:00)应用验证。 但是我需要在退出字段后验证输入标记,此时它在用户输入时验证。 知道如何解决这个问题吗?

  <label for="operativeToTime">Operative to time</label>
    <input name="operativeToTime"
           ng-model="deviceDetails.operativeToTime"
           type="text"
           ng-pattern="/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/"
           ng-required="true">
    <div class="error-container" ng-show="editDeviceForm.operativeToTime.$invalid">
        <span class="error" ng-show="editDeviceForm.operativeToTime.$error.required">Operative to time is required</span>
        <span class="error" ng-show="editDeviceForm.operativeToTime.$invalid">+++++++++++++Wrong format</span>
     </div>

2 个答案:

答案 0 :(得分:1)

你想要的是ng-blur,内置于:https://docs.angularjs.org/api/ng/directive/ngBlur

<label for="operativeToTime">Operative to time
    <input name="operativeToTime"
           ng-model="deviceDetails.operativeToTime"
           type="text"
           ng-required="true"
           ng-blur="validateInput(this)"/>
    <div class="error-container" ng-show="editDeviceForm.operativeToTime.$invalid">
        <span class="error" ng-repeat="error in errors" ng-bind="error"></span>
     </div>

更新 - 根据OP的要求添加JS: 您需要在这些行上添加一些内容来将错误绑定到您的范围:

$scope.errors = [];
$scope.validateInput = function(element){
var validate1 = //your logic for validation here
if(!validate1){$scope.errors.push("Error message 1");}
var validate2 = //your logic for validation here
if(!validate2){$scope.errors.push("Error message 2");}
};

答案 1 :(得分:1)

我使用不同的方法,自定义指令解决了它。因为我必须在这里保持DRY方法我的代码;


app.directive('checkTimeOnBlur', function () {
    var EMAIL_REGX = /^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/;
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            elm.unbind('input').unbind('keydown').unbind('change');

            elm.bind('blur', function () {
                scope.$apply(function () {
                    if (EMAIL_REGX.test(elm.val())) {
                        ctrl.$setValidity('time', true);
                    } else {
                        ctrl.$setValidity('time', false);
                    }
                });
            });
        }
    };
});

在视图中:

     <input type="text" name="time" ng-model="user.time" check-time-on-blur>
        <span ng-show="editDeviceForm.time.$error.time" class="help-inline">Invalid time!!!</span>

此plnkr http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview

激发了解决方案