I am trying to write an isolated directive that will run regex to validate certain input fields. I want the directive to know what regex to match up on and use based on an attribute on the input.
a sample input would look like this.
<input required tabindex="5" regex-validation regex="validationRegex.zipRegex" ng-model="payment.zip" type="text" />
below is a sample from the directive where it sets up a controller to match on then the directive itself. scope.regex.test logs undefined.
module.controller('Controller', function($scope) {
$scope.validationRegex = {
americanExpressRegex: new RegExp(/^(?!3[47]).*$/),
cvvRegex: new RegExp(/^[0-9]{3,4}$/),
currencyRegex: new RegExp(/^[$]?\d{0,18}\.?\d{0,2}$/),
cityRegex: new RegExp(/^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/),
zipRegex: new RegExp(/^[0-9]{5}(?:-[0-9]{4})?$/),
phoneRegex: new RegExp(/^(\d(\s|\.|\-)?)?\(?\d{3}\)?(\s|\.|\-)?\d{3}(\s|\.|\-)?\d{4}$/),
/* jshint ignore:start */
emailRegex: new RegExp("^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$"),
/* jshint ignore:end */
numberRegex: new RegExp(/^\d+$/),
addressRegex: new RegExp(/^[A-Za-z0-9 \-_\.,]{0,55}$/),
bankAccountRegex: new RegExp(/^[0-9]{1,17}$/),
routingNumberRegex: new RegExp(/^((0[0-9])|(1[0-2])|(2[1-9])|(3[0-2])|(6[1-9])|(7[0-2])|80)([0-9]{7})$/)
};
})
.directive('regexValidation', [function () {
return {
scope: { regex: "=" },
link: function (scope, element) {
element.bind('change', function () {
console.log(scope.regex);
//grab the element we are working with into a jquery element
var ele = $(element);
//grab the element value for multiple future use
var value = ele.val();
//if we have a value check with regex
if (value && !**scope.regex.test**(value)) {
ele.parent().addClass("error");
}
//this will set the element back to how it was and check to see if all validation is
//complete
else {
ele.parent().removeClass("error");
}
});
}
};
}]);