| 2 |
lars |
1 |
/*
|
|
|
2 |
* Lets you say "either at least X inputs that match selector Y must be filled,
|
|
|
3 |
* OR they must all be skipped (left blank)."
|
|
|
4 |
*
|
|
|
5 |
* The end result, is that none of these inputs:
|
|
|
6 |
*
|
|
|
7 |
* <input class="productinfo" name="partnumber">
|
|
|
8 |
* <input class="productinfo" name="description">
|
|
|
9 |
* <input class="productinfo" name="color">
|
|
|
10 |
*
|
|
|
11 |
* ...will validate unless either at least two of them are filled,
|
|
|
12 |
* OR none of them are.
|
|
|
13 |
*
|
|
|
14 |
* partnumber: {skip_or_fill_minimum: [2,".productinfo"]},
|
|
|
15 |
* description: {skip_or_fill_minimum: [2,".productinfo"]},
|
|
|
16 |
* color: {skip_or_fill_minimum: [2,".productinfo"]}
|
|
|
17 |
*
|
|
|
18 |
* options[0]: number of fields that must be filled in the group
|
|
|
19 |
* options[1]: CSS selector that defines the group of conditionally required fields
|
|
|
20 |
*
|
|
|
21 |
*/
|
|
|
22 |
$.validator.addMethod( "skip_or_fill_minimum", function( value, element, options ) {
|
|
|
23 |
var $fields = $( options[ 1 ], element.form ),
|
|
|
24 |
$fieldsFirst = $fields.eq( 0 ),
|
|
|
25 |
validator = $fieldsFirst.data( "valid_skip" ) ? $fieldsFirst.data( "valid_skip" ) : $.extend( {}, this ),
|
|
|
26 |
numberFilled = $fields.filter( function() {
|
|
|
27 |
return validator.elementValue( this );
|
|
|
28 |
} ).length,
|
|
|
29 |
isValid = numberFilled === 0 || numberFilled >= options[ 0 ];
|
|
|
30 |
|
|
|
31 |
// Store the cloned validator for future validation
|
|
|
32 |
$fieldsFirst.data( "valid_skip", validator );
|
|
|
33 |
|
|
|
34 |
// If element isn't being validated, run each skip_or_fill_minimum field's validation rules
|
|
|
35 |
if ( !$( element ).data( "being_validated" ) ) {
|
|
|
36 |
$fields.data( "being_validated", true );
|
|
|
37 |
$fields.each( function() {
|
|
|
38 |
validator.element( this );
|
|
|
39 |
} );
|
|
|
40 |
$fields.data( "being_validated", false );
|
|
|
41 |
}
|
|
|
42 |
return isValid;
|
|
|
43 |
}, $.validator.format( "Please either skip these fields or fill at least {0} of them." ) );
|