Skip to content

Commit f26c419

Browse files
committed
now possible to validate number selected options in multiple select lists, and some other small things refactored, created minified version
1 parent 7153b7b commit f26c419

File tree

5 files changed

+129
-84
lines changed

5 files changed

+129
-84
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ This plugin was created to minimize javascript logic in the html code when deali
4646
* Show help information automatically when input is focused
4747
* Validate given values immediately when input is blurred.
4848
* Make validation optional by adding attribute data-validation-optional="true" to the element. This means that the validation defined in data-validation only will take place in case a value is given.
49+
* Make validation dependent on another input of type checkbox being checked by adding attribute data-validation-if-checked="name of checkbox input"
4950

5051

5152
## Validate inputs on blur
@@ -158,7 +159,9 @@ var jQueryFormLang = {
158159
badCustomVal : 'You gave an incorrect answer',
159160
badInt : 'Incorrect integer value',
160161
badSecurityNumber : 'Your social security number was incorrect',
161-
badUKVatAnswer : 'Incorrect UK VAT Number'
162+
badUKVatAnswer : 'Incorrect UK VAT Number',
163+
badNumberOfSelectedOptionsStart : 'You have to choose at least ',
164+
badNumberOfSelectedOptionsEnd : ' answers'
162165
};
163166
```
164167

example.html

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@
22
<html>
33
<head>
44

5-
<title>Form validator plugin for jQuery</title>
5+
<title>Form validation using jQuery</title>
66

77
<meta charset="UTF-8"/>
88
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
99

1010
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
11-
<script type="text/javascript" src="jquery.formvalidator.min.js?upd=2"></script>
11+
<script type="text/javascript" src="jquery.formvalidator.min.js?upd=1.5"></script>
1212

13-
<link href="style.css?upd=2" type="text/css" rel="stylesheet"/>
13+
<link href="style.css?upd=1.5" type="text/css" rel="stylesheet"/>
1414

1515
</head>
1616
<body>
1717

1818
<h1>
19-
Form validation using jQuery
19+
jQuery Form Validation (v 1.5)
2020
</h1>
2121
<p>
2222
<a href="https://github.com/victorjonsson/jQuery-Form-Validator/">
@@ -152,9 +152,13 @@ <h2>Example of all features</h2>
152152
</select>
153153
</p>
154154
<p>
155-
<strong>These features applies to select lists with multiple options as well</strong>
155+
<strong>These features applies to select lists with multiple options as well.
156+
You have to select at least two answers from this list and you'r not allowed
157+
to select &quot;* Not allowed&quot;</strong>
156158
<br />
157-
<select name="something" multiple="multiple" size="5" data-validation="validate_int">
159+
<em>validate_num_answers num2 validate_int</em>
160+
<br />
161+
<select name="something" multiple="multiple" size="5" data-validation="validate_num_answers num2 validate_int">
158162
<option value="">- - Select something - -</option>
159163
<option value="1">Green</option>
160164
<option value="2">Blue</option>
@@ -164,6 +168,18 @@ <h2>Example of all features</h2>
164168
<option value="red">* Not allowed</option>
165169
</select>
166170
</p>
171+
<p>
172+
<strong>Website, optional (this input will only be validated if it has a value)</strong>
173+
<em>data-validation-optional=&quot;true&quot; data-validation=&quot;validate_url&quot;</em>
174+
<input type="text" data-validation="validate_url" data-validation-optional="true"/>
175+
</p>
176+
<p>
177+
<strong>E-mail (this input will not be validated unless this checkbox is checked
178+
<input type="checkbox" name="my_checkbox" value="1" />)</strong>
179+
<br />
180+
<em>data-validation-if-checked=&quot;my_checkbox&quot; data-validation=&quot;validate_email&quot;</em>
181+
<input type="text" data-validation="validate_email" data-validation-if-checked="my_checkbox"/>
182+
</p>
167183
<p>
168184
<strong>Length restriction</strong>
169185
<span class="chars_left">
@@ -208,16 +224,16 @@ <h2>
208224

209225
<p>
210226
<strong>When will you arrive</strong>
211-
<em>The answer given on the question below will only be validated if this option is unchecked</em>
227+
<em>The answer given on the question below will only be validated if this option is checked</em>
212228
<input type="checkbox" name="disable_hours" checked="checked"/>
213229
</p>
214230

215231
<p>
216232
<strong>Time HH:mm</strong> <em>validate_time</em><br/>
217-
<input type="text" data-validation="validate_time" name="hours"/>
233+
<input type="text" data-validation-if-checked="disable_hours" data-validation="validate_time" name="hours"/>
218234
</p>
219235
<p>
220-
<strong>Date (optional)</strong> <em>validate_date - This input will only be validated if it has a value</em><br/>
236+
<strong>Date yyyy-mm-dd (optional)</strong> <em>validate_date - This input will only be validated if it has a value</em><br/>
221237
<input type="text" data-validation="validate_date" data-validation-optional="true" data-validation-error-msg="If you want to leave a date, it has to be correct" name="opt_date"/>
222238
</p>
223239
<p>
@@ -228,17 +244,9 @@ <h2>
228244
<script>
229245
var validationSettings = {
230246
errorMessagePosition : 'element',
231-
borderColorOnError : '',
232-
ignore: ['hours']
247+
borderColorOnError : ''
233248
};
234249

235-
$('input[name=disable_hours]').change(function() {
236-
if($(this).is(':checked'))
237-
validationSettings.ignore.push('hours');
238-
else
239-
validationSettings.ignore = [];
240-
});
241-
242250
$('#custom_form')
243251
.submit(function() {
244252
if ($(this).validate(false, validationSettings))

jquery.formvalidator.js

Lines changed: 96 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
*
77
* Dual licensed under the MIT or GPL Version 2 licenses
88
*
9-
* $version 1.4
9+
* $version 1.5
1010
*/
1111
(function($) {
1212
$.extend($.fn, {
@@ -180,27 +180,6 @@
180180
// get updated dialog strings
181181
language = jQueryFormUtils.LANG;
182182

183-
/**
184-
* Tells whether or not to validate element with this name and of this type
185-
*
186-
* @param {String} name
187-
* @param {String} type
188-
* @param {Object} config
189-
* @return {Boolean}
190-
*/
191-
var ignoreInput = function(name, type, config) {
192-
if (type === 'submit' || type === 'button') {
193-
return true;
194-
}
195-
196-
for (var i = 0; i < config.ignore.length; i++) {
197-
if (config.ignore[i] === name) {
198-
return true;
199-
}
200-
}
201-
return false;
202-
};
203-
204183
/**
205184
* Adds message to error message stack if not already in the message stack
206185
*
@@ -778,87 +757,141 @@ jQueryFormUtils.validateDomain = function(val) {
778757
return true;
779758
};
780759

760+
/**
761+
* <input data-validation="length12" /> => getAttribute($(element).attr('class'), 'length') = 12
762+
* @param {String} attrValue
763+
* @param {String} attrName
764+
* @returns {Number}
765+
*/
766+
jQueryFormUtils.attrInt = function(attrValue, attrName) {
767+
var regex = new RegExp('(' + attrName + '[0-9\-]+)', "g");
768+
return attrValue.match(regex)[0].replace(/[^0-9\-]/g, '');
769+
};
770+
781771
/**
782772
* Validate the value of given element according to the validation rule
783773
* defined in attribute with given name. Will return true if valid,
784-
* error message otherwise
774+
* error message otherwise.
785775
*
786-
* @param {jQuery} el
776+
* Notice!
777+
* This function is a wrapper around jQueryFormUtils.validate that makes
778+
* it possible to handle select elements with multiple values
779+
*
780+
* @param {jQuery} el - Element containing the value (input,select,textarea)
787781
* @param {Object} language (jQueryFormUtils.LANG)
788782
* @param {Object} config
789-
* @param {jQuery} form
783+
* @param {jQuery} form - Optional
790784
* @return {String}|{Boolean}
791785
*/
792786
jQueryFormUtils.validateInput = function(el, language, config, form) {
787+
var values = el.val();
788+
values = values || ''; // coerce to empty string if null
789+
790+
if( !(values instanceof Array) ) {
791+
values = [values];
792+
}
793+
794+
// Validate select with multiple values
795+
if( el.get(0).nodeName == 'SELECT' && el.attr('multiple') ) {
796+
var validationRules = el.attr(config.validationRuleAttribute);
797+
var validationErrorMsg = el.attr(config.validationErrorMsgAttribute);
798+
if(validationRules.indexOf('validate_num_answers') > -1) {
799+
var num = jQueryFormUtils.attrInt(validationRules, 'num');
800+
if(num > values.length) {
801+
return validationErrorMsg || (language.badNumberOfSelectedOptionsStart +num+ language.badNumberOfSelectedOptionsEnd);
802+
}
803+
}
804+
}
805+
806+
807+
for(var i=0; i < values.length; i++) {
808+
var validation = jQueryFormUtils.validate(values[i], el, language, config, form);
809+
if(validation !== true)
810+
return validation;
811+
}
812+
813+
return true;
814+
};
815+
816+
/**
817+
* Validate the value of given element according to the validation rule
818+
* defined in attribute with given name. Will return true if valid,
819+
* error message otherwise
820+
*
821+
* @see jQueryFormUtils.validateInput
822+
*
823+
* @param {String} value
824+
* @param {jQuery} el - Element containing the value (input,select,textarea)
825+
* @param {Object} language (jQueryFormUtils.LANG)
826+
* @param {Object} config
827+
* @param {jQuery} form - Optional
828+
* @return {String}|{Boolean}
829+
*/
830+
jQueryFormUtils.validate = function(value, el, language, config, form) {
793831

794-
var value = el.val();
795832
var optional = el.attr("data-validation-optional");
796833

797834
// test if a checkbox forces this element to be validated
798-
var validate_if_checked = 0; // set initial value false
835+
var validationDependsOnCheckedInput = false;
836+
var validationDependentInputIsChecked = false;
799837
// get value of this element's attribute "... if-checked"
800-
var validate_if_checked_el_name = el.attr("data-validation-if-checked");
801-
// get the form closest to this element
802-
var thisform = el.closest("form");
838+
var validateIfCheckedElementName = el.attr("data-validation-if-checked");
803839
// make sure we can proceed
804-
if (validate_if_checked_el_name != null && thisform != null) {
840+
if (validateIfCheckedElementName != null) {
841+
842+
// Set the boolean telling us that the validation depends
843+
// on another input being checked
844+
validationDependsOnCheckedInput = true;
845+
846+
// Form not given as argument
847+
if(!form)
848+
form = el.closest("form");
849+
805850
// select the checkbox type element in this form
806-
var validate_if_checked_el_obj = thisform.find('input[name="' + validate_if_checked_el_name + '"]');
807-
// test if it's property "checked" is checked
808-
if ( validate_if_checked_el_obj.prop('checked') )
809-
{ // set value for validation checkpoint
810-
validate_if_checked = 1;
811-
}
812-
} // end if depend_checked_el_name not null
851+
var validateIfCheckedElement = form.find('input[name="' + validateIfCheckedElementName + '"]');
813852

853+
// test if it's property "checked" is checked
854+
if ( validateIfCheckedElement.prop('checked') ) {
855+
// set value for validation checkpoint
856+
validationDependentInputIsChecked = true;
857+
}
858+
}
814859

815-
// validation checkpoint (added extra criteria depend_check)
816-
// if empty AND optional AND does not depend on a checkbox being checked, it is ok, return true
817-
if ((value === null || value.length == 0) && optional === 'true' && !validate_if_checked) {
860+
// validation checkpoint
861+
// if empty AND optional attribute is present
862+
// OR depending on a checkbox being checked AND checkbox is checked, return true
863+
if ((!value && optional === 'true') || (validationDependsOnCheckedInput && !validationDependentInputIsChecked)) {
818864
return true;
819865
}
820866

821-
value = value || ''; // coerce to empty string if null
822-
823867
var validationRules = el.attr(config.validationRuleAttribute);
824868

825869
// see if form element has inline err msg attribute
826870
var validationErrorMsg = el.attr(config.validationErrorMsgAttribute);
827871

828872
if (typeof validationRules != 'undefined' && validationRules !== null) {
829873

830-
/**
831-
* <input data-validation="length12" /> => getAttribute($(element).attr('class'), 'length') = 12
832-
* @param {String} attrValue
833-
* @param {String} attrName
834-
* @returns {Number}
835-
*/
836-
var getAttributeInteger = function(attrValue, attrName) {
837-
var regex = new RegExp('(' + attrName + '[0-9\-]+)', "g");
838-
return attrValue.match(regex)[0].replace(/[^0-9\-]/g, '');
839-
};
840-
841874
// Required
842875
if (validationRules.indexOf('required') > -1 && value === '') {
843876
// return custom inline err msg if defined
844877
return validationErrorMsg || language.requiredFields;
845878
}
846879

847880
// Min length
848-
if (validationRules.indexOf('validate_min_length') > -1 && value.length < getAttributeInteger(validationRules, 'length')) {
849-
return validationErrorMsg || language.tooShortStart + getAttributeInteger(validationRules, 'length') + language.tooShortEnd;
881+
if (validationRules.indexOf('validate_min_length') > -1 && value.length < jQueryFormUtils.attrInt(validationRules, 'length')) {
882+
return validationErrorMsg || language.tooShortStart + jQueryFormUtils.attrInt(validationRules, 'length') + language.tooShortEnd;
850883
}
851884

852885
// Max length
853-
if (validationRules.indexOf('validate_max_length') > -1 && value.length > getAttributeInteger(validationRules, 'length')) {
854-
return validationErrorMsg || language.tooLongStart + getAttributeInteger(validationRules, 'length') + language.tooLongEnd;
886+
if (validationRules.indexOf('validate_max_length') > -1 && value.length > jQueryFormUtils.attrInt(validationRules, 'length')) {
887+
return validationErrorMsg || language.tooLongStart + jQueryFormUtils.attrInt(validationRules, 'length') + language.tooLongEnd;
855888
}
856889

857890
// Length range
858891
if (validationRules.indexOf('validate_length') > -1) {
859-
var range = getAttributeInteger(validationRules, 'length').split('-');
892+
var range = jQueryFormUtils.attrInt(validationRules, 'length').split('-');
860893
if (value.length < parseInt(range[0],10) || value.length > parseInt(range[1],10)) {
861-
return validationErrorMsg || language.badLength + getAttributeInteger(validationRules, 'length') + language.tooLongEnd;
894+
return validationErrorMsg || language.badLength + jQueryFormUtils.attrInt(validationRules, 'length') + language.tooLongEnd;
862895
}
863896
}
864897

@@ -976,7 +1009,9 @@ jQueryFormUtils.LANG = {
9761009
badCustomVal : 'You gave an incorrect answer',
9771010
badInt : 'Incorrect integer value',
9781011
badSecurityNumber : 'Your social security number was incorrect',
979-
badUKVatAnswer : 'Incorrect UK VAT Number'
1012+
badUKVatAnswer : 'Incorrect UK VAT Number',
1013+
badNumberOfSelectedOptionsStart : 'You have to choose at least ',
1014+
badNumberOfSelectedOptionsEnd : ' answers'
9801015
};
9811016

9821017

0 commit comments

Comments
 (0)