jQuery Validator Setup and Configuration
To begin using jQuery Validator, include both jQuery and jQuery Validator libraries in your project.
Creating Custom Validation Methods
Define custom validation logic using the addMethod function:
$.validator.addMethod(
"dateRangeValidation",
function (inputValue, formElement) {
var startDateField = $('#startDate').val();
var endDateField = $('#endDate').val();
if (startDateField === '' && endDateField === '') {
return false;
} else {
return true;
}
}
);
Form Structure Example
<form id="userForm">
<div class="form-field">
<label class="field-label">Document Validity Period<span class="required">*</span></label>
<input id="startDate" name="startDate" class="date-input form-control" autocomplete="off" style="width: 200px;">
<input id="endDate" name="endDate" class="date-input form-control" autocomplete="off" style="width: 200px;">
</div>
</form>
<button onclick="validateForm()">Submit</button>
Form Validation Implementation
Trigger validation on form submisison:
function validateForm() {
$("#userForm").valid();
}
Initialiez validation rules when the page loads:
$(document).ready(function () {
$("#userForm").validate({
rules: {
startDate: {
required: true,
dateRangeValidation: true
}
},
messages: {
startDate: {
required: "Document start date is required",
dateRangeValidation: "Document validity period must be specified"
}
},
errorElement: "span",
errorPlacement: function (errorMessage, fieldElement) {
errorMessage.addClass("validation-error");
if (fieldElement.prop("type") === "checkbox") {
errorMessage.insertAfter(fieldElement.parent("label"));
} else {
errorMessage.insertAfter(fieldElement);
}
},
highlight: function (fieldElement, errorClass, validClass) {
$(fieldElement).addClass("field-error");
},
unhighlight: function (fieldElement, errorClass, validClass) {
$(fieldElement).removeClass("field-error");
}
});
});