I’m struggling with a custom jQuery validator, its my first go at one and I think I’m pretty close. I’m trying to validate a number (bid) against a minimum bid for a auction system I’m building, the problem is the minimum bid is always a decimal number for example 15.50 but the bid could be a whole number 16. I think my logic is falling over as I’m validating a whole against a decimal I’ve tried to conver the number entered to a decimal but that seems to break everything. Below is a copy of my function.
$.validator.addMethod("bidgreaterthan", function (value, element, params) {
var parts = element.name.split(".");
var bid = value.toFixed(2);
var prefix = "";
if (parts.length > 1)
prefix = parts[0] + ".";
var currentbidvalue = $('input[name="' + prefix + params.propertytested + '"]').val();
if (!bid || !currentbidvalue)
return true;
if (bid < (currentbidvalue))
return false;
});
I might be well off and it could be something else thats the problem but any help would be appreciated.
Comparing a float (number with decimals) and an integer (whole number) in Javascript should work without any conversion.
However, calling
val()on an input field might yield a string. If you’re not sure what format the numbers you’re about to compare are in, it’s always a good idea to force a conversion into a float (although Javascript might convert for you):This should be the safest method also in your case, since even converting an integer into a float with naturally still return the proper result as the following is true:
So in your case you might be able to do something along the lines of:
The check for the existence of value / bid value should probably occur before doing any conversions, though.