Reputation: 3991
I am learning angularjs. Here i am faing a problem in validation.
I have a textbox which take input for postcode and after validating it return a true false value.
i have defined the function inside the controller but getting no idea how o call it on textbox
<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
function have different regex pattern it check if math return true else false.
How do i achieve validation.
Upvotes: 0
Views: 275
Reputation: 499
The easiest way is bind the validate
function to input
's event, such as:
<input ng-change='checkPostCodeError' or ng-keyup='checkPostCodeError' />
Furthermore, you can use $watch
to watch the myprofile.postCode
instead.
But, form controls are specially treated in angular. That means angular has many built-in validation function/directives. And you can create your own validation directive.
Here is a demo:
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>
Upvotes: 1