A jQuery plugin to use the HTML5 required attribute and require one of many elements
Say you have form with two inputs: telephone number and mobile number. You want the user to enter at least one
of those numbers, but you don't want to make both fields required. This plugin will set both fields as required but
will still allow the form to be submitted as long as one of them is filled.
- jquery.grouprequired.min.js (1.47kB, 662B gzipped)
- jquery.grouprequired.js (4.27kB, 1.3kB gzipped)
<script src="https://unpkg.com/jquery-grouprequired@2.4.0/dist/jquery.grouprequired.min.js"></script>
<!-- OR -->
<script src="https://unpkg.com/jquery-grouprequired@2.4.0/dist/jquery.grouprequired.js"></script>Install via yarn:
$ yarn add jquery-grouprequiredInstall via NPM:
$ npm install jquery-grouprequired --save<form>
Telephone: <input type="tel" name="telephone" value="" required><br>
Mobile: <input type="tel" name="mobile" value="" required><br>
<input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://unpkg.com/jquery-grouprequired@2.4.0/dist/jquery.grouprequired.min.js"></script>
<script>
$(function () {
$('input[type=tel]').groupRequired({
errorMessage: 'Please enter at least one contact number'
});
});
</script>$ yarn add jquery-grouprequiredvar $ = require('jquery');
require('jquery-grouprequired')($);
$('input[type=tel]').groupRequired();| Option | Type | Description | Default |
|---|---|---|---|
| errorMessage | string|function |
Custom error message | '' |
| requiredFilter | function |
Function which returns a boolean dictating whether the group of elements should be required. | null |
| namespace | string |
Unique plugin namespace for events and data | 'groupRequired' |
Using the errorMessage option as a function:
$('input[type=tel]').groupRequired({
errorMessage: function (pluginInstance, event) {
// do some logic checking with function arguments
// 'this' is bound to the current input element
return 'Please enter a number';
}
});Modify the $.fn.groupRequired object to change default option values:
$.fn.groupRequired.namespace = 'my_namespace';Released under the MIT license