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