How can I extend AngularJS model flags on an Angular form? - angularjs

AngularJS provides what they call 'model flags' on their forms. For example, you can have formName.$dirty, formName.$invalid, etc. What I want to know is how can I create my own custom flag for my AngularJS forms? A high level demonstration or link to an article would be a sufficient answer.

See here: how-to-add-custom-validation-to-an-angular-js-form.
In short, this is a custom valitation directive example:
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var blacklist = attr.blacklist.split(',');
// for DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
return value;
});
}
};
});
And this it's an example of it's usage:
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
<span ng-show="myForm.fruitName.$error.blacklist">
The phrase "{{data.fruitName}}" is blacklisted</span>
<span ng-show="myForm.fruitName.$error.required">required</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
But, again, read the referenced question and accepted answer, it's by far more complete...

Related

AngularJS Custom Validation Directive with http post

I'm trying to validate a form input field generated by ng-repeat which is using a custom directive to handle the validation, as it requires quite specific formatting.
I've got the whole flow mostly working, but I can't get the final step to display the error message for each field. Here are some snippets from the code...
Part of the template:
<form class="form-horizontal" name="vehicle.form" ng-submit="submitForm(vehicle.form.$valid)" novalidate>
<div class="vehicles_row" ng-repeat="vehicle in rows" ng-class-odd="'row_odd'" ng-class-even="'row_even'">
<div class="vehicles_table_cell">
<ng-form name="vrmFieldForm">
<label>Vehicle Registration</label>
<input type="text" name="vrm" ng-model="vehicle.vrm" required dr-vrm-format />
<div class="control-group messages" ng-messages="vrmFieldForm.vrm.$error" ng-if="submitted">
<span ng-message="required">Required field</span>
<span ng-message="format">Invalid format</span>
</div>
</ng-form>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-primary" ng-click="addRow()">Add Row</button>
<button type="submit" class="btn btn-primary" ng-disabled="btn_disabled">Save all Vehicles</button>
</div>
</form>
The Custom Directive:
angular.module('vehiclesApp').directive('drVrmFormat', function($http) {
// Matches function to loop through array until VRM pattern is found
var matches = function(registration, patterns) {
var vrm = registration.toUpperCase().replace(/\s+/g, ''),
i = patterns.length,
pattern = false;
while(i--) {
if(vrm.match(patterns[i])) {
pattern = true;
break;
}
}
return pattern;
};
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.format = function(modelValue) {
$http.post('/Fleet/ValidateVrm.php', modelValue)
.then(function(response) {
if(matches(modelValue, response.data)) {
console.log('Valid');
return true;
}
console.log('Invalid');
return false;
});
};
}
};
});
The http post service calls a script which queries a database and returns a JSON encoded array of regex patterns based on the data being sent in the modelValue. Each input value is then run through the 'matches' function to see if the format entered matched one of the possible patterns.
I know this is working as I can see the valid/invalid output in the console for as many rows created by the ng-repeat. However when I try to return the response to the UI, the error messages are not displaying, even when there is an error.
One more thing...
I took this from another example which tests for odd/even input values and this Does work.
angular.module('vehiclesApp').directive('drVrmFormat', function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.format = function(modelValue) {
return modelValue % 2 === 1;
};
}
};
});
It's able to identify whether each input in the repeating form has an error and display a message next to each one accordingly. So I know I'm very close with this, I just need a way to communicate the true/false bool to the UI (I think). Any help much appreciated.

Setting form field to required with custom directive

I have a directive that queries google maps api with the form field value (event_postcode). It needs to be a required field. Yet when the field is populated, and maps api (via manageEventsSrv.getPostcodeLocation()) returns a valid address, the forms submit button remains disabled, i.e. form is invalid.
My directive:
app.directive('geoLocatePostcode', ['manageEventsSrv', function(manageEventsSrv) {
return {
restrict: 'A',
require: 'ngModel',
link : function(scope, elem, attrs, ctrl){
var valid = false;
ctrl.$parsers.unshift(function(value) {
if(value.length>=3){
manageEventsSrv.getPostcodeLocation(value+',uk').then(function(result){
valid = true;
scope.point = new Parse.GeoPoint({latitude:result.lat,longitude:result.lng}); // parse.com geopoint
ctrl.$setValidity('locationNotFound', true);
}, function(result){
valid = false;
ctrl.$setValidity('locationNotFound', false);
});
} else {
ctrl.$setValidity('locationNotFound', true);
valid = false;
}
return valid ? value : undefined;
});
}
}
}]);
Form field:
<input type="text" placeholder="First 4 Characters Only" ng-model="event_postcode" maxlength="4" name="event_postcode" required geo-locate-postcode>
<span data-ng-show="createEventForm.event_postcode.$error.locationNotFound">Location not found</span>
<button type="submit" class="button" ng-disabled="createEventForm.$invalid">Create</button>
I assume i am not implementing "required" properly when using a custom directive.
Think i might have got to the bottom of this.... i needed to change
return valid ? value : undefined; to return valid ? value : false;

Is there a better way to validate this angular form?

I have a working solution for validating each field on keyup in a form in angularjs. I feel it can be better though. Are there any more clever ways?
The HTML:
<input type="text" placeholder="First Name" ng-keyup="validateFirstName($event) "ng-model="user.firstName"/>
<i ng-class="firstNameValidation" class="icon placeholder-icon padding"></i>
<input type="text" placeholder="Last Name"/>
<i ng-class="lastNameValidation" class="icon placeholder-icon padding"></i>
<input type="email" placeholder="Email"/>
<i ng-class="emailValidation" class="icon placeholder-icon padding"></i>
And in the controller i have:
$scope.user = {}
$scope.firstNameValidation = "ion-arrow-left-a text-danger"
$scope.lastNameValidation = "ion-arrow-left-a text-danger"
$scope.emailValidation = "ion-arrow-left-a text-danger"
$scope.validateFirstName = ($event) ->
if $scope.user.firstName.trim().length > 2
$scope.firstNameValidation = "ion-checkmark-circled text-success"
else
$scope.firstNameValidation = "ion-arrow-left-a text-danger"
...
And so on, a function for each field of the input validation. I feel like there is too much redundancy.
Any ideas?
The AngularJS team provide you with a small set of predefined
validators that you can use out of the box and I recommend you to take
a look at their documentation at
https://docs.angularjs.org/api/ng/directive/input
There's a great article over at year of moo with a more in-depth
view and explanation on how this is done in 1.3
The fun part
Here's a simple and dirty plunkr to show you the 1.2.x way i action
Given the following template
<form name="myForm">
<!-- Notice my custom validator named max-length -->
<input type="text" name="firstName" ng-model="firstName"
max-length="20"
ng-class="myForm.firstName.$error.maxLength ? 'ion-arrow-left-a text-danger' : 'ion-checkmark-circled text-success'"
/>
</form>
here's how you do it in Angular 1.2.x
angular
.module('App')
.directive('maxLength', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var maxLength = parseInt(attr.maxLength);
//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var validity = validate(value);
ngModel.$setValidity('maxLength', validity);
return validity ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
var validity = validate(value);
ngModel.$setValidity('maxLength', validity);
return value;
});
function validate(value) {
return value.trim().length < maxLength;
}
}
};
});
and here's how it's done in Angular 1.3.x
angular
.module('App')
.directive('maxLength', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var maxLength = parseInt(attr.maxLength);
ngModel.$validators.maxLength(function(value) {
return validate(value, maxLength);
});
function validate(value, maxLength) {
return value.trim().length < maxLength;
}
}
};
});
To conclude
Now, what I've shown you is one way, and the way the angular team thinks of custom validation according to their documentation but, one size doesn't fit all and there are other ways to do this validation. One such way is to make use of 3rd party modules like the one Marcel-Stör mentioned in his answer.
Best of luck to you on your road to mastering custom validation in angularjs :)
It may be a matter of style or preference but I suggest you give valdr a try. I'm quite convinced it offers the features you're looking for - particularly if redundancy bothers you.

Custom form validation in AngularJS

I have created one custom directive to validate the "domain" name form field.
form field element as
<input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" >
custom directive code is
app.directive('domainValidate', function() {
return {
// 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.domainValidateFlags || 'i';
// create the regex obj.
var regex = new RegExp(attr.domainValidate, 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('domainValidate', 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.
console.log(value)
ctrl.$setValidity('domainValidate', regex.test(value));
// return the value or nothing will be written to the DOM.
return value;
});
}
};
});
I want to validate the field on form submit as well on value change.
The above code is not working, please can any one help me what is the error in above code or
let me know how to validate the domain name field
thanks
oldish post and i'm noob at angular, but try this
<form name="userForm" ng-submit="submit()" novalidate>
<div>
<input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$" required>
<div ng-show="userForm.domain.$error.domainValidate">invalid domain</div>
<div ng-show="userForm.domain.$dirty && userForm.domain.$error.required">required</div>
</div>
<button type="submit">Submit</button>
</form>
then js directive
app.directive('domainValidate', function () {
return {
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
//get the regex flags from the regex-validate-flags="" attribute (optional)
var flags = attr.domainValidateFlags || 'i';
// create the regex obj.
var regex = new RegExp(attr.domainValidate, flags);
function setValidity(value) {
ctrl.$setValidity('domainValidate', regex.test(value));
}
scope.$watch(attr.ngModel, function (newValue, oldValue) {
if (newValue !== undefined && newValue !== oldValue) {
setValidity(newValue);
}
});
scope.submit = function () {
setValidity(ctrl.$modelValue);
for (var error in ctrl.$error) {
if (ctrl.$error[error]) return;
}
// send stuff
}
}
};
});
My suggestion is: Instead of custom directive validation use default URL validation:
<input type="url" autofocus name="domain" ng-model="user.domain">
Or if you don't want to use it, share your code in fiddle.

How to add custom validation to an AngularJS form?

I have a form with input fields and validation setup by adding the required attributes and such. But for some fields I need to do some extra validation. How would I "tap in" to the validation that FormController controls?
Custom validation could be something like "if these 3 fields are filled in, then this field is required and needs to be formatted in a particular way".
There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it. Creating a custom directive and using NgModelController looks like another option, but would basically require me to create a directive for each custom validation rule, which I do not want.
Actually, marking a field from the controller as invalid (while also keeping FormController in sync) might be the thing that I need in the simplest scenario to get the job done, but I don't know how to do that.
Edit: added information about ngMessages (>= 1.3.X) below.
Standard form validation messages (1.0.X and above)
Since this is one of the top results if you Google "Angular Form Validation", currently, I want to add another answer to this for anyone coming in from there.
There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it.
It's "public", no worries. Use it. That's what it's for. If it weren't meant to be used, the Angular devs would have privatized it in a closure.
To do custom validation, if you don't want to use Angular-UI as the other answer suggested, you can simply roll your own validation directive.
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var blacklist = attr.blacklist.split(',');
//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
return value;
});
}
};
});
And here's some example usage:
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
<span ng-show="myForm.fruitName.$error.blacklist">
The phrase "{{data.fruitName}}" is blacklisted</span>
<span ng-show="myForm.fruitName.$error.required">required</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
Note: in 1.2.X it's probably preferrable to substitute ng-if for ng-show above
Here is an obligatory plunker link
Also, I've written a few blog entries about just this subject that goes into a little more detail:
Angular Form Validation
Custom Validation Directives
Edit: using ngMessages in 1.3.X
You can now use the ngMessages module instead of ngShow to show your error messages. It will actually work with anything, it doesn't have to be an error message, but here's the basics:
Include <script src="angular-messages.js"></script>
Reference ngMessages in your module declaration:
var app = angular.module('myApp', ['ngMessages']);
Add the appropriate markup:
<form name="personForm">
<input type="email" name="email" ng-model="person.email" required/>
<div ng-messages="personForm.email.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
In the above markup, ng-message="personForm.email.$error" basically specifies a context for the ng-message child directives. Then ng-message="required" and ng-message="email" specify properties on that context to watch. Most importantly, they also specify an order to check them in. The first one it finds in the list that is "truthy" wins, and it will show that message and none of the others.
And a plunker for the ngMessages example
Angular-UI's project includes a ui-validate directive, which will probably help you with this. It let's you specify a function to call to do the validation.
Have a look at the demo page: http://angular-ui.github.com/, search down to the Validate heading.
From the demo page:
<input ng-model="email" ui-validate='{blacklist : notBlackListed}'>
<span ng-show='form.email.$error.blacklist'>This e-mail is black-listed!</span>
then in your controller:
function ValidateCtrl($scope) {
$scope.blackList = ['bad#domain.example','verybad#domain.example'];
$scope.notBlackListed = function(value) {
return $scope.blackList.indexOf(value) === -1;
};
}
You can use ng-required for your validation scenario ("if these 3 fields are filled in, then this field is required":
<div ng-app>
<input type="text" ng-model="field1" placeholder="Field1">
<input type="text" ng-model="field2" placeholder="Field2">
<input type="text" ng-model="field3" placeholder="Field3">
<input type="text" ng-model="dependentField" placeholder="Custom validation"
ng-required="field1 && field2 && field3">
</div>
You can use Angular-Validator.
Example: using a function to validate a field
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "myCustomValidationFunction(form.firstName)">
Then in your controller you would have something like
$scope.myCustomValidationFunction = function(firstName){
if ( firstName === "John") {
return true;
}
You can also do something like this:
<input type = "text"
name = "firstName"
ng-model = "person.firstName"
validator = "'!(field1 && field2 && field3)'"
invalid-message = "'This field is required'">
(where field1 field2, and field3 are scope variables. You might also want to check if the fields do not equal the empty string)
If the field does not pass the validator then the field will be marked as invalid and the user will not be able to submit the form.
For more use cases and examples see: https://github.com/turinggroup/angular-validator
Disclaimer: I am the author of Angular-Validator
I recently created a directive to allow for expression-based invalidation of angular form inputs. Any valid angular expression can be used, and it supports custom validation keys using object notation. Tested with angular v1.3.8
.directive('invalidIf', [function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var argsObject = scope.$eval(attrs.invalidIf);
if (!angular.isObject(argsObject)) {
argsObject = { invalidIf: attrs.invalidIf };
}
for (var validationKey in argsObject) {
scope.$watch(argsObject[validationKey], function (newVal) {
ctrl.$setValidity(validationKey, !newVal);
});
}
}
};
}]);
You can use it like this:
<input ng-model="foo" invalid-if="{fooIsGreaterThanBar: 'foo > bar',
fooEqualsSomeFuncResult: 'foo == someFuncResult()'}/>
Or by just passing in an expression (it will be given the default validationKey of "invalidIf")
<input ng-model="foo" invalid-if="foo > bar"/>
Here's a cool way to do custom wildcard expression validations in a form (from: Advanced form validation with AngularJS and filters):
<form novalidate="">
<input type="text" id="name" name="name" ng-model="newPerson.name"
ensure-expression="(persons | filter:{name: newPerson.name}:true).length !== 1">
<!-- or in your case:-->
<input type="text" id="fruitName" name="fruitName" ng-model="data.fruitName"
ensure-expression="(blacklist | filter:{fruitName: data.fruitName}:true).length !== 1">
</form>
app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ngModelController) {
scope.$watch(attrs.ngModel, function(value) {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelController.$setValidity('expression', booleanResult);
});
}
};
}]);
jsFiddle demo (supports expression naming and multiple expressions)
It's similar to ui-validate, but you don't need a scope specific validation function (this works generically) and ofcourse you don't need ui.utils this way.
#synergetic I think #blesh suppose to put function validate as below
function validate(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
}
ngModel.$formatters.unshift(validate);
ngModel.$parsers.unshift(validate);
Update:
Improved and simplified version of previous directive (one instead of two) with same functionality:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Example usage:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.
Test expression has local $model variable which you should use to compare it to other variables.
Previously:
I've made an attempt to improve #Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Example how to use it to make cross validated fields:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression is executed to validate model when ng-model or any of ensure-watch variables is changed.
Custom Validations that call a Server
Use the ngModelController $asyncValidators API which handles asynchronous validation, such as making an $http request to the backend. Functions added to the object must return a promise that must be resolved when valid or rejected when invalid. In-progress async validations are stored by key in ngModelController.$pending. For more information, see AngularJS Developer Guide - Forms (Custom Validation).
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
For more information, see
ngModelController $asyncValidators API
AngularJS Developer Guide - Forms (Custom Validation).
Using the $validators API
The accepted answer uses the $parsers and $formatters pipelines to add a custom synchronous validator. AngularJS 1.3+ added a $validators API so there is no need to put validators in the $parsers and $formatters pipelines:
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$validators.blacklist = function(modelValue, viewValue) {
var blacklist = attr.blacklist.split(',');
var value = modelValue || viewValue;
var valid = blacklist.indexOf(value) === -1;
return valid;
});
}
};
});
For more information, see AngularJS ngModelController API Reference - $validators.
In AngularJS the best place to define Custom Validation is Cutsom directive.
AngularJS provide a ngMessages module.
ngMessages is a directive that is designed to show and hide messages
based on the state of a key/value object that it listens on. The
directive itself complements error message reporting with the ngModel
$error object (which stores a key/value state of validation errors).
For custom form validation One should use ngMessages Modules with custom directive.Here i have a simple validation which will check if number length is less then 6 display an error on screen
<form name="myform" novalidate>
<table>
<tr>
<td><input name='test' type='text' required ng-model='test' custom-validation></td>
<td ng-messages="myform.test.$error"><span ng-message="invalidshrt">Too Short</span></td>
</tr>
</table>
</form>
Here is how to create custom validation directive
angular.module('myApp',['ngMessages']);
angular.module('myApp',['ngMessages']).directive('customValidation',function(){
return{
restrict:'A',
require: 'ngModel',
link:function (scope, element, attr, ctrl) {// 4th argument contain model information
function validationError(value) // you can use any function and parameter name
{
if (value.length > 6) // if model length is greater then 6 it is valide state
{
ctrl.$setValidity('invalidshrt',true);
}
else
{
ctrl.$setValidity('invalidshrt',false) //if less then 6 is invalide
}
return value; //return to display error
}
ctrl.$parsers.push(validationError); //parsers change how view values will be saved in the model
}
};
});
$setValidity is inbuilt function to set model state to valid/invalid
I extended #Ben Lesh's answer with an ability to specify whether the validation is case sensitive or not (default)
use:
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="Coconuts,Bananas,Pears" caseSensitive="true" required/>
code:
angular.module('crm.directives', []).
directive('blacklist', [
function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
'blacklist': '=',
},
link: function ($scope, $elem, $attrs, modelCtrl) {
var check = function (value) {
if (!$attrs.casesensitive) {
value = (value && value.toUpperCase) ? value.toUpperCase() : value;
$scope.blacklist = _.map($scope.blacklist, function (item) {
return (item.toUpperCase) ? item.toUpperCase() : item
})
}
return !_.isArray($scope.blacklist) || $scope.blacklist.indexOf(value) === -1;
}
//For DOM -> model validation
modelCtrl.$parsers.unshift(function (value) {
var valid = check(value);
modelCtrl.$setValidity('blacklist', valid);
return value;
});
//For model -> DOM validation
modelCtrl.$formatters.unshift(function (value) {
modelCtrl.$setValidity('blacklist', check(value));
return value;
});
}
};
}
]);
Some great examples and libs presented in this thread, but they didn't quite have what I was looking for. My approach: angular-validity -- a promise based validation lib for asynchronous validation, with optional Bootstrap styling baked-in.
An angular-validity solution for the OP's use case might look something like this:
<input type="text" name="field4" ng-model="field4"
validity="eval"
validity-eval="!(field1 && field2 && field3 && !field4)"
validity-message-eval="This field is required">
Here's a Fiddle, if you want to take it for a spin. The lib is available on GitHub, has detailed documentation, and plenty of live demos.

Resources