I have spent hours trying to achieve the following validation using a custom validator method:
There are two dropdowns a user can select:
- Current Location (Where user currently is)
- Destination (Where user intends going)
What I am trying to achieve:
The validator should not allow a user to select the same location for both dropdowns except Location 1.
For example:
A user can select that he is going from Location 1 to Location 1. (Can travel to a different place in this location because this location is large).
But he cannot select that he is going from:
Location 2 to Location 2.
Location 3 to Location 3.
Location 4 to Location 4.
Location 5 to Location 5.
These locations do not have different places in the same location.
He can go from Location 1 to any of these other locations, vice-versa, or can go from Location to location, i.e Location 3 to Location 4.
Can you please help me out with this? What I have done so far is quite poor and not even working. The custom method is not working, I need to add rules and messages but do not know how.
Thanks in advance for any help!
What I have done so far:
HTML
<form id="rideForm" action="#">
<select id="3" name="currentLocation">
<option value ="" class="inputDefault">Select Location</option>
<option value="Location1">Location 1</option>
<option value="Location2">Location 2</option>
<option value="Location3">Location 3</option>
<option value="Location4">Location 4</option>
<option value="Location5">Location 5</option>
</select>
<select id="4" name="destination">
<option value ="" class="inputDefault">Select Destination</option>
<option value="Location1">Location 1</option>
<option value="Location2">Location 2</option>
<option value="Location3">Location 3</option>
<option value="Location4">Location 4</option>
<option value="Location5">Location 5</option>
</select>
</form
JS/JQuery Code
$(document).ready(function() {
$.validator.addMethod("validSelection", function(value, element) {
if ($('select[name="currentLocation"]').val() == $('select[name="destination"]').val()) {
return true;
} else {
return false;
}
});
("#rideForm").validate(
{
rules:
{
currentLocation:
{
required: true,
// validSelection: true
},
destination:
{
required: true,
// validSelection: true
}
},
messages: {
currentLocation: {
required: "Please select your current location",
},
destination: {
required: "Please select a destionation",
}
}
});
});