I am currently working on creating a custom directive that will perform regex validation on specific input fields. The goal is for the directive to determine which regex pattern to use based on an attribute provided in the input element.
Here is an example of how an input field using this directive might look:
<input required tabindex="5" regex-validation regex="validationRegex.zipRegex" ng-model="payment.zip" type="text" />
Below is a snippet from the directive implementation where it initializes a controller with various regex patterns and defines the directive itself. However, there seems to be an issue with scope.regex.test returning 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");
}
});
}
};
}]);