2014-11-17 58 views
0

我正在学习angularjs。在这里,我正在验证中遇到问题。如何调用输入标签的验证功能

我有一个输入邮编的文本框,并验证它后返回一个真正的错误值。

我已经定义了控制器内部的功能,但越来越不知道如何O调用它的文本框

<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功能有不同的正则表达式检查它是否数学返回true,否则返回false。

我如何实现验证。

回答

1

最简单的方法是绑定validate功能input的事件,如:

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

此外,还可以使用$watch观看myprofile.postCode代替。

但是,表单控件是特殊处理的角度。这意味着角度有许多内置的验证功能/指令。你可以创建你自己的验证指令。

这里是一个演示:

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> 
+0

为什么你使用'$ parsers'这个?你可以使用'$ validators'来代替。 –

+0

@RahilWazir'$ validators'也可以使用。 – creeper

+0

@creeper感谢您的快速指南我只是想问你是否使用了后验代码验证,但我并不理解你在哪里声明它是使用创建指令为postCodeValidation –