This is a quick post on how I was able to get ParsleyJS validation working with AngularJS. I used Parsley.js 2.x and Angular.js 1.3.x and 1.4.x.
How to use it
Then all you need is to add “parsley-validate” to your form element as an attribute and then parsley will be tied to that form.
For example:
<form parsley-validate>
<!-- normal form elements here -->
</form>
Note
- Will load parsley when the form is loaded from angularjs.
- This takes care of the dynamic inserting of forms into the page.
Code
var angularParselyModule = angular.module('parsley', []);
angularParselyModule.parsleyOptions = {
priorityEnabled: false,
errorsWrapper: '<ul class="parsley-error-list"></ul>'
};
angularParselyModule.directive('parsleyValidate', ['$timeout', function($timeout) {
return {
restrict: 'A',
require: '?form',
link: function(scope, elm, attrs, formController) {
elm.bind('$destroy', function() {
formController.parsley.destroy();
});
if(!formController.parsley) {
formController.parsley = new Parsley(elm[0], angularParselyModule.parsleyOptions);
$timeout(function() {formController.parsley.validate()}, 100);
}
scope.$on('feedReceived', function() {
if(!formController.parsley) {
formController.parsley = new Parsley(elm[0], angularParselyModule.parsleyOptions);
}
formController.parsley.validate();
});
}
};
}]);
//We register our parsley logic for various element types.
angularParselyModule.directive('input', parsleyFieldDirective);
angularParselyModule.directive('textarea', parsleyFieldDirective);
angularParselyModule.directive('select', parsleyFieldDirective);
function parsleyFieldDirective($timeout) {
return {
restrict: 'E',
require: '^?form',
link: function (scope, elm, attrs, formController) {
if(formController.parsley) {
$timeout(function() {formController.parsley.validate()}, 150); // Need to validate after the data is in the dom.
}
}
};
}
Final Thoughts
Now with AngularJS 1.3+ we have much better form validation. The benefit of ParsleyJS is that it allows for messages to be reused much more easily then even in the new Angular 1.3. Since the Angular forms are much better integrated with HTML5, I ended up moving in that direction. In order to reuse the messages, ngMessage module can be used with Angular and is much better at reuse though, I made some slight changes to make it even more reusable. Hopefully I will share that in another post.
How can one get Parsley validation to work with ng-require?
Hi Ryan
Thank you for sharing your script – it works great. I would just like to change the form validation styles – but I’m struggling a lot. I posted my question here:
http://stackoverflow.com/questions/35180866/customize-parsley-form-validation-styles-in-angularjs-module
Please help – I would appreciate it so much!
Is there a way to implement parselyjs with angularjs 2/4
I haven’t tried. I would recommend using the built in reactive forms.