JSFiddle - React, Tailwind, and code Playground
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="\bblah\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';
$scope.data = $scope.data || {};
$scope.formEntities = [{
"Value": "Koningsmantel",
"Name": "deliveryStreet",
"LocalizedName": "Aansluitstraat",
"Type": "String",
"Validation": {},
"ValidationErrorMessages": {},
"Extra": {
"ReadOnly": true
}
}, {
"Value": "5",
"Name": "deliveryHouseNumber",
"LocalizedName": "Aansluithuisnr",
"Type": "String",
"Validation": {},
"ValidationErrorMessages": {},
"Extra": {
"ReadOnly": true
}
}, {
"Value": null,
"Name": "deliveryHouseNumberAddition",
"LocalizedName": "Aansluithuisnr toev",
"Type": "String",
"Validation": {},
"ValidationErrorMessages": {},
"Extra": {}
}, {
"Value": "2403HZ",
"Name": "deliveryZipCode",
"LocalizedName": "Postcode",
"Type": "String",
"Validation": {
"Required": true
},
"ValidationErrorMessages": {
"Required": "'Postcode' is verplicht"
},
"Extra": {}
}, {
"Value": "Alphen aan den Rijn",
"Name": "deliveryCity",
"LocalizedName": "Aansluitplaats",
"Type": "String",
"Validation": {
"Required": true
},
"ValidationErrorMessages": {
"Required": "'Plaats' is verplicht"
},
"Extra": {}
}];
});
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...