My code consists of two input fields and a submit button. The business rules require the following rules: 1. One or both fields must be filled out. Both cannot be blank. 2. If the first field is empty, then the second field must have a value greater than or equal to 50. 3. If the second field is empty, then the second field must have a value greater than or equal to 500.
I’ve implemented the jQuery to retrieve the minimum amounts from data-rule- in each field in the HTML. These values will ultimately be managed by a CMS. The same goes for the validation messages.
My code behaves exactly as I want it and passes my unit tests, but I am wondering if the code could be simplified. I see that the code where foo and bar are assigned is repeated throughout the script. I tried to move them to variables outside of the validator logic, but it affected functionality and no longer behaved as needed. My guess is that the variables aren’t updated at the same times that the validator code is executed. So I’m not sure where else I could put these variables so that the code isn’t repeated.
Is this possible?
$ .validator.addMethod('genrule', function(value, element, param) { return (value >= param); }); /* var tempfoo = $ .trim($ ('#foo').val()); var foo = tempfoo.length > 0 ? parseInt(tempfoo, 10) : 0; var tempbar = $ .trim($ ('#bar').val()); var bar = tempbar.length > 0 ? parseInt(tempbar, 10) : 0; */ $ ('#test').validate({ rules: { foo: { required: function(element) { var tempbar = $ .trim($ ('#bar').val()); var bar = tempbar.length > 0 ? parseInt(tempbar, 10) : 0; return bar === 0; }, genrule: { param: $ ('#foo').data('rule-genrule'), depends: function(element) { var tempfoo = $ .trim($ ('#foo').val()); var foo = tempfoo.length > 0 ? parseInt(tempfoo, 10) : 0; var tempbar = $ .trim($ ('#bar').val()); var bar = tempbar.length > 0 ? parseInt(tempbar, 10) : 0; return foo !== 0 || bar === 0; } } }, bar: { required: function(element) { var tempfoo = $ .trim($ ('#foo').val()); var foo = tempfoo.length > 0 ? parseInt(tempfoo, 10) : 0; return foo === 0; }, genrule: { param: $ ('#bar').data('rule-genrule'), depends: function(element) { var tempfoo = $ .trim($ ('#foo').val()); var foo = tempfoo.length > 0 ? parseInt(tempfoo, 10) : 0; var tempbar = $ .trim($ ('#bar').val()); var bar = tempbar.length > 0 ? parseInt(tempbar, 10) : 0; return foo === 0 || bar !== 0; } } } }, submitHandler: function(form) { alert('Success'); return false; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script> <form id="test"> <input id="foo" name="foo" type="text" data-rule-genrule="500" data-msg-genrule="Foo must be >= 500" data-msg-required="Foo custom required" /> <br/> <input id="bar" name="bar" type="text" data-rule-genrule="50" data-msg-genrule="Bar must be >= 50" data-msg-required="Bar custom required" /> <br/> <input type="submit" /> </form>