AngularJS Dynamic Form Validation Based from Select box -
i have straightforward directive ensure basic sanity checks on whether form field contains valid phone number or valid email depending on select box option chosen (email or text).
issue arises after valid email or phone number entered corresponding selection made, , other choice selected, field being validated remains valid though should not valid entry longer.
i stuck @ how have field revalidate through directive when select option changed.
my directive follows:
directive("rpattern", function() { return { restrict: "a", require: "ngmodel", scope: { service: '=' }, link: function(scope, el, attrs, ctrl) { var validator, patternvalidator, pattern; scope.$watch(function() { if (scope.service == 'text') { pattern = new regexp(/^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/); } else if (scope.service == 'email') { pattern = new regexp(/^[a-za-z0-9._-]+@[a-za-z0-9.-]+\.[a-za-z]{2,6}$/); } }); patternvalidator = function(value) { return validate(pattern, value); }; ctrl.$formatters.push(patternvalidator); ctrl.$parsers.push(patternvalidator); function validate(regexp, value) { if (value == null || value === "" || regexp.test(value)) { ctrl.$setvalidity('pattern', true); return value; } else { ctrl.$setvalidity('pattern', false); return; } } } } })
any appreciated!
edit plunker has been created here: http://plnkr.co/edit/q7cmj8t5tzkkxmuolzgf?p=preview
have tried put call validate inside watch like:
directive("rpattern", function() { return { restrict: "a", require: "ngmodel", scope: { service: '=' }, link: function(scope, el, attrs, ctrl) { var validator, patternvalidator, pattern; scope.$watch(function() { if (scope.service == 'text') { pattern = new regexp(/^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/); } else if (scope.service == 'email') { pattern = new regexp(/^[a-za-z0-9._-]+@[a-za-z0-9.-]+\.[a-za-z]{2,6}$/); } patternvalidator = function(value) { return validate(pattern, value); }; ctrl.$formatters.push(patternvalidator); ctrl.$parsers.push(patternvalidator); }); function validate(regexp, value) { if (value == null || value === "" || regexp.test(value)) { ctrl.$setvalidity('pattern', true); return value; } else { ctrl.$setvalidity('pattern', false); return; } } } } })
Comments
Post a Comment