Reputation: 12672
I am trying to validate a date that is separated into three fields (year, month, and day, of course). I cannot change these fields, as much as I'd like to. I am using the jQuery Validation plugin (also not by my choice). I cannot figure how to validate all three fields as one. Even validating them individually would suffice.
My HTML is as follows.
<div class="date-field requiredField">
<div class="date-picker hasDatepicker" id="dp1412187717156" style="display: none;">...</div>
<input type="text" class="month" required="required" maxlength="2" placeholder="MM" title="Month" value="1">
/
<input type="text" class="day" required="required" maxlength="2" placeholder="DD" title="Day" value="1">
/
<input type="text" class="year" required="required" placeholder="YYYY" title="Year" value="1973">
<span class="date-pick-button"></span>
<span class="date-clear-button"></span>
</div>
I am invoking the validator as follows:
$("#SignUp_Enrollment").validate({
focusInvalid : false,
rules: {
co_ssn: {
ssn: true
},
first_name: {
required: true
},
last_name: {
required: true
}
// some more rules
},
invalidHandler: function (form, validator) {
// style the invalid fields
},
submitHandler: function (form) {
form.submit();
}
});
I am of course validating other fields, but this plugin is not showing me any mercy. I've tried adding month, day, and year rules to no avail. Any suggestions on what direction to take?
Upvotes: 0
Views: 1508
Reputation: 98738
Quote OP:
"Even validating them individually would suffice."
Your code is broken because none of the fields in your HTML markup contain a name
attribute. A unique name
is mandatory in order for this plugin to operate. It's how it keeps track of the input elements.
See: http://jqueryvalidation.org/reference/#markup-recommendations
It's not shown in your markup, but all relevant input elements must also be contained within <form></form>
tags. This plugin will not work otherwise.
Since you already have the date saved into an hidden field, you can also just validate the hidden field.
<input type="hidden" name="myDate" />
Activate validation on hidden fields by using the ignore: []
option.
Then as long as this hidden field has a unique name
attribute, you can apply validation rules the same as you would on any other field.
Use the errorPlacement
callback to precisely place the message attached to the hidden field.
Upvotes: 2
Reputation: 1238
You can merge this three fields to one (hidden
input), and validate this input
var day, month, year;
day = $('.day').val();
month = $('.month').val();
year = $('.year').val();
$('.hidden-date-input').val([day, year, month].join('-'));
Upvotes: -1