Angular.js Data Model Based Validation infrastructure
View the Project on GitHub nadavsinai/ndValidation
Writing forms in large applications is tiresome - one must repeat the same validation directives for each model property for each form the model is included. and even worse one must also include the same validation error user messages with their relevant display logic. making changes becomes laborious... for example some code from angular.js docs site
<form name="form" class="css-form" novalidate>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required/><br/>
<div ng-show="form.uEmail.$dirty && form.uEmail.$invalid">Invalid:
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
</form>
if using nd-validate this boils down to
<input type="email" ng-model="user.email" nd-validate/>
the validation rules and messages are configured once per data model,
for example for this model it would look like this
User.prototype.$validationConfig = {
email:{required:'Tell us your email.'},
format:{type:'email',message:'This is not a valid email.'}
}
The place in which this is declared is quite dynamic although I do
recommend to cast proper data-models, validation configuration can be put on the scope and referenced from
directive's attribute.
The directive will:
with bower one can install using
bower install nd-validate
add the script tag and add the module 'ndValidation' as dependency to your app.
On an input field (within or out of a form) add the nd-validation attribute to automatically add validation rules and associated messages by the model validation definition the default is an object found on the prototype of the model instance called $validationConfig, (this can be set via the ndValidationSvc.setDefaultValidationSource at config time). or, alternatively using a validation object which is found on the scope and is refered to in the attribute's value e.g nd-validation='config.get("user").validation'
Special note on Ng-repeat and such repeaters- if a model appears more than once in page's scope (like in ng-repeat) you must make sure the models are unique - in NgRepeat we add '_'+$index to the input name automatically
This should be an object with keys representing the input names (model properties) and values being either - a string (simple message, eg for required), - a hash with options an message (eg. for length : {min:5,message:'must be longer than 5'}) - an array with many validation hashes as above.
The following validations are supported :