如何对输入标记调用验证函数

How to call a validation function on input tag

本文关键字:调用 验证 函数 输入      更新时间:2023-09-26

我正在学习angularjs。在这里,我在验证中遇到了一个问题。

我有一个文本框,它接受邮政编码的输入,并在验证后返回一个真正的假值。

我已经在控制器内部定义了函数,但不知道如何在文本框上调用它

<input type="text" placeholder="Postcode" ng-model="myprofile.postCode"  >
.controller("MyProfileCtrl", function ($scope, $rootScope) {
        $scope.myprofile = {};
        $scope.myprofile.postCode = "";
        $scope.checkPostCodeError = function(){
            var newPostCode = checkPostCode  ($scope.myprofile.postCode); // calling a javascript function
            if (newPostCode) {
                $scope.myprofile.postCode = newPostCode;
                return true;
            }
            else return false;
  }

checkPostCode函数具有不同的正则表达式模式,它会检查数学是否返回真或假。

如何实现验证。

最简单的方法是将validate函数绑定到input的事件,例如:

<input ng-change='checkPostCodeError' or ng-keyup='checkPostCodeError' />

此外,您可以使用$watch来观看myprofile.postCode

但是,表单控件是专门以角度处理的。这意味着angular有许多内置的验证函数/指令。您可以创建自己的验证指令。

这是一个演示:

app.directive('postCodeValidation', function () {
    function checkPostCodeError(postCode) {
        if(/*your check logic*/) {
            return true;
        } else {
            return false;
        }
    }
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                if (checkPostCodeError(viewValue)) {
                    // it is valid
                    ctrl.$setValidity('postCode', true);
                    return viewValue;
                } else {
                    // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('postCode', false);
                    return undefined;
                }
            });
        }
    };
});
// how to use in template
<form>
<input type="text" placeholder="Postcode" ng-model="myprofile.postCode" name="postCode" post-code-validation/><br /><span ng-show="form.postCode.$error.postCode">This is not valid postCode!</span>
</form>