If you want to avoid boiler-plate obtrusive code in your html you can avoid placing all those ng-show and things like that in your form totally decoupling it from the validation mechanism itself.
You don't need to necessarily be tied to angular when performing validation in the client side, you can combine angularjs with any other JS framework and make them work together as independent modules with requireJS. I've been using bootstrapValidator together with angular, binding them with requireJS, and it performs well, giving you a clean code in your html, with totally decoupled modules , you can attach a listener when your view is loaded using $viewContentLoaded , then you enable validation on your form using a function call, I'm posting a sample code as an example:
a clean angularJS form:
<form id="myForm" novalidate="novalidate" class="form-horizontal">
<label>name</label>
<input type="text" class="form-control" id="name" name="name" ng-model="rec.name" />
<label>description</label>
<textarea rows="5" id="description" ng-model="rec.description" name="description"> </textarea>
// ... more fields
in your controller code:
controllers.controller('MyCtrl', ['$scope', 'MyService',
function($scope, MyService) {
// ... controller code
// setup validator based on your page form
$scope.$on('$viewContentLoaded', loadFormValidator);
}]);
function loadFormValidator(){
$('#myForm').bootstrapValidator({
message: 'The form has invalid inputs',
fields: {
name: {
message: 'The name is not valid',
validators: {
notEmpty: {
message: 'The name is required and can\'t be empty'
},
stringLength: {
min: 6,
max: 70,
message: 'The name must be more than 6 and less than 70 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.\s]+$/,
message: 'The name can only consist of alphabetical, number, dot, spaces and underscore'
}
}
},
description: {
message: 'The description is not valid',
validators: {
notEmpty: {
message: 'The description is required and can\'t be empty'
},
stringLength: {
min: 6,
max: 160,
message: 'The description must be more than 6 and less than 160 characters long'
}
}
},
price: {
message: 'The price is not valid',
validators: {
notEmpty: {
message: 'The price is required and can\'t be empty'
},
regexp: {
regexp: /^\d+(,\d{1,2})?$/,
message: 'The price can only consist of digits or , to indicate fraction values'
}
}
}
});
};
function isFormValid(){
// Get plugin instance
var bootstrapValidator = $('#myForm').data('bootstrapValidator');
bootstrapValidator.validate();
// validate and then call method is Valid to check results
return bootstrapValidator.isValid();
};
you might encapsulate the above code in a requireJS module or in a JS namespace or even inside a angular service. In your controller you can call "isFormValid" to check if all inputs are correct for that specific form:
/* callback for ng-click on your controller: */
$scope.saveRecord = function () {
// validate fields
if (isFormValid()) {
MyService.save($scope.record);
// ...
}
};