diff --git a/build/example.htm b/build/example.htm index 760504e..5199dcf 100644 --- a/build/example.htm +++ b/build/example.htm @@ -19,7 +19,7 @@ - + - \ No newline at end of file + diff --git a/src/jquery.validity.core.js b/src/jquery.validity.core.js index 1fee51f..9f0013e 100644 --- a/src/jquery.validity.core.js +++ b/src/jquery.validity.core.js @@ -99,6 +99,7 @@ $.validity = { messages:{ require:"#{field} is required.", + requireOne:"At least one field is required.", // Format validators: match:"#{field} is in an invalid format.", @@ -324,6 +325,22 @@ $.fn.extend({ ); }, + // At least one of these fields should be filled + requireOne:function(msg) { + var valid = validate( + this, + (function() { + var group = this; + // Uses serializeArray to filter out unchecked checkboxes + return !!($(group).serializeArray().filter(function(e) { return e.value }).length); + }).bind(this), + // Uses bind to ignore validate(), we don't want validation errors + // when some inputs are not filled, only when none are. + msg || $.validity.messages.requireOne + ); + return valid.length ? this : []; + }, + // Validate whether the field matches a regex. match:function(rule, msg) { diff --git a/src/jquery.validity.css b/src/jquery.validity.css index 057c186..0d9352a 100644 --- a/src/jquery.validity.css +++ b/src/jquery.validity.css @@ -39,7 +39,7 @@ label.error { * an extra bit of text (or anything really) that explains what the summary is. * '.validity-erroneous' is applied to every input that fails. */ -.validity-summary-container { display:none; } +.validity-summary-container { } .validity-summary-output ul { } .validity-erroneous { border:solid 2px #f56600 !important; } diff --git a/tests/index.html b/tests/index.html index 37150ea..303ff0e 100644 --- a/tests/index.html +++ b/tests/index.html @@ -24,6 +24,7 @@ + diff --git a/tests/unit-tests/common/requireOne.js b/tests/unit-tests/common/requireOne.js new file mode 100644 index 0000000..5dae4ea --- /dev/null +++ b/tests/unit-tests/common/requireOne.js @@ -0,0 +1,27 @@ +module("common", { setup:setup8Inputs }); + +test("$.fn.requireOne()", 3, function() { + var expected, result; + + $('#qunit-fixture input:odd').val('a value'); + $('#qunit-fixture input:even').val(''); + $.validity.start(); + $('#qunit-fixture input').requireOne(); + result = $.validity.end().errors; + expected = 0; + equal(result, expected, "require validation passes when some imputs are filled"); + + $('#qunit-fixture input').val(''); + $.validity.start(); + $('#qunit-fixture input').require(); + result = $.validity.end().errors; + expected = 8; + equal(result, expected, "require validation fails on all inputs when all are empty"); + + $('#qunit-fixture input').val('value'); + $.validity.start(); + $('#qunit-fixture input').require(); + result = $.validity.end().errors; + expected = 0; + equal(result, expected, "require validation does not fail when there are not empty inputs"); +});