Tips for using Parsleyjs

I been using parsley.js recently for some complex form validation , just want to share some of the tips that help.

1. If you checking on radio or checkbox as required field, using the min-check validation rather than using required validation.

2. if you just need to validate field that are visible, don’t use the auto validation, write the parsley function that kick in before submit, add checking element is visible on the listener.

3. For select input that having default value, if you need to check there are valid value selected , add the function on validators , to make sure there is value available for the input option.

$('#contactform').parsley({
//exclude input type , file ?
excluded: 'input[type=hidden]',
validators: {
// for #3 ,checking the input must have value , example dropdown list with "Select this" kind of option should be no value so that it can be skipped
checkdefault: function (val, checkdefault) {
if (val[0] === '') return false;
else return true;
}
},
messages: {
checkdefault: "This value should be a multiple of %s"
},
listeners: {
onFieldValidate: function (elem) {
//for #2 ,checking and make sure the parent div is not hidden
if (elem.parents('div.ishidden:eq(0)').length > 0 && !elem.parents('div.ishidden:eq(0)').is(':visible')) {
return true;
}
return false;
},
onFormSubmit: function (isFormValid, event, focusedField) {},
onFieldError: function (elem, constraint) {}
}
});
view raw parsley.js hosted with ❤ by GitHub

4.  Last if you want to add validation on the fly for certain field, you can use

$( '#field' ).parsley( 'addConstraint', { required: true } );

to remove the “required” validation on the fly.

$( '#field' ).parsley( 'removeConstraint', 'required' );

You may also like...