Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script>
$(function () {
$.validator.addMethod('validDate', function (value, element) {
return this.optional(element) || /^(0?[1-9]|1[012])[ /](0?[1-9]|[12][0-9]|3[01])[ /][0-9]{4}$/.test(value);
}, 'Please provide a date in the mm/dd/yyyy format');
$.validator.addMethod('dateBefore', function (value, element, params) {
// if end date is valid, validate it as well
var end = $(params);
if (!end.data('validation.running')) {
$(element).data('validation.running', true);
setTimeout($.proxy(
function () {
this.element(end);
}, this), 0);
// Ensure clearing the 'flag' happens after the validation of 'end' to prevent endless looping
setTimeout(function () {
$(element).data('validation.running', false);
}, 0);
}
return this.optional(element) || this.optional(end[0]) || new Date(value) < new Date(end.val());
}, 'Must be before corresponding end date');
$.validator.addMethod('dateAfter', function (value, element, params) {
// if start date is valid, validate it as well
var start = $(params);
if (!start.data('validation.running')) {
$(element).data('validation.running', true);
setTimeout($.proxy(
function () {
this.element(start);
}, this), 0);
setTimeout(function () {
$(element).data('validation.running', false);
}, 0);
}
return this.optional(element) || this.optional(start[0]) || new Date(value) > new Date($(params).val());
}, 'Must be after corresponding start date');
$('#myform').validate({ // initialize the plugin
rules: {
startDate: {
dateBefore: '#endDate',
required: true
},
endDate: {
dateAfter: '#startDate',
required: true
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="startDate" id="startDate" class="validDate" />
<br/>
<input type="text" name="endDate" id="endDate" class="validDate" />
<br/>
<input type="submit" />
</form>
</body>
</html>
Most Helpful This Week
How can I redirect the user from one page to another using jQuery or pure JavaScript?
JavaScript check if first string contains all characters of second string
How to change the height of Textarea on click?
Check if a string ends with the given target string
Edit the text of label on click using jQuery
JavaScript sort multi dimensional array on specific columns