Add custom multiple validation with Parsley

Is it possible to add a custom multiple test (i.e. one test that depends on multiple inputs) using Parsley?

Sometimes I would like to check a <form> or the section as a whole and provide an error at this level, and not at the <input> level.

For example, imagine a form with <table> that allows the user to enter various combinations of color and size. Let's say I want to check for duplicate combinations. The best way would be to check the line against the line and search for a duplicate line above it. If duplicate lines are found, these whole lines are invalid, without any separate input, actually invalid for each declaration. Moreover, changing any field may make this or another row invalid.

If I try to add, say, "tr.combination" to the inputs parameter, <table> fields will not be added. It seems that the parameters are not passed to the constructor, so it does not return a ParsleyField and instead returns a common Parsley object.

I can’t even build ParsleyFieldMultiple since the selector is hard-coded and the code is very dependent on checkbox / radio

+5
source share
1 answer

What you are trying to accomplish cannot be done due to parsley. Given that this seems like a really specific situation, you may need the following solution:

  • Instead of creating a custom validator, use Parsley events to perform this check
  • Based on the existence of duplicate combinations, set up ParsleyForm.validationResult .

This is not the most elegant solution, but I consider it the simplest. Actually, I don’t think you can find an elegant solution to this problem.

You can check this on working jsfiddle .

 // bind event after form validation $.listen('parsley:form:validated', function(ParsleyForm) { // We only do this for specific forms if (ParsleyForm.$element.attr('id') == 'myForm') { var combinations = []; // foreach tr ParsleyForm.$element.find('tr').each(function() { var tr = $(this); // if there are any inputs if (tr.find('input').length > 0) { // Add a new combination based on tr inputs combinations.push(tr.find('input:first').val() + '|' + tr.find('input:last').val()); } }); // sort array combinations = combinations.sort(); // check if there are duplicate combinations for (var i = 0; i < combinations.length - 1; i++) { // if two combinations are equal, show message // and force validation result to false if (combinations[i + 1] == combinations[i]) { ParsleyForm.validationResult = false; $("#form-message-holder") .html('There are some errors with your form') .css('display', 'block'); return false; } } // otherwise, validation result is true and hide the error message ParsleyForm.validationResult = true; $("#form-message-holder") .html('') .css('display', 'none'); } }); 
+3
source

Source: https://habr.com/ru/post/1207347/


All Articles