Angular - Custom Regex Validation directive
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<form name="myForm" ng-submit="doSomething()">
<label>Must contain the word <strong>blah</strong> (case insensitive)
<br/>
<!-- set up the input, make sure it:
1. has ng-model
2. has a name="" so we can reference it in the model.
3. has regex-validate
4. (optional) has regex-validate-flags -->
<input type="text" placeholder="Enter text here"
ng-model="test" name="test" regex-validate="\b'^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$\b" regex-validate-flags="i"/>
</label>
<!-- set up some sort of output for validation
the format here is: [formName].[fieldName].$error.[validationName]
where validation name is determined by
ctrl.$setValidity(validationName, true/false) in your
custom directive.
-->
<span style="color:red" ng-show="myForm.test.$error.regexValidate">WRONG!</span>
<div>
<!-- for added measure, disable the submit if the form is $invalid -->
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
</div>
</div>
CSS
* {
font-family: Verdana, Helvetica, Arial, sans-serif;
line-height: 2em;
}
strong {
font-weight: bold;
}
JavaScript
/* Try, Catch, Fail: Angular Custom Validation via Directives */
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.test = 'this is wrong';
});
app.directive('regexValidate', function() {
return {
// restrict to an attribute type.
restrict: 'A',
// element must have ng-model attribute.
require: 'ngModel',
// scope = the parent scope
// elem = the element the directive is on
// attr = a dictionary of attributes on the element
// ctrl = the controller for ngModel.
link: function(scope, elem, attr, ctrl) {
//get the regex flags from the regex-validate-flags="" attribute (optional)
var flags = attr.regexValidateFlags || '';
// create the regex obj.
var regex = new RegExp(attr.regexValidate, flags);
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function(value) {
// test and set the validity after update.
var valid = regex.test(value);
ctrl.$setValidity('regexValidate', valid);
// if it's valid, return the value to the model,
// otherwise return undefined.
return valid ? value : undefined;
});
// add a formatter that will process each time the value
// is updated on the DOM element.
ctrl.$formatters.unshift(function(value) {
// validate.
ctrl.$setValidity('regexValidate', regex.test(value));
// return the value or nothing will be written to the DOM.
return value;
});
}
};
});