I need to add a new field onto an existing web form. This field (numeric) must be completed before saving, but only for new documents. Existing documents shouldn’t be considered.
So, I know I need to compare dates and check for an empty field, but I also need to make sure that there is no more than 4 digits in the field, no negative numbers, no text, and no zero, i.e. 0 entered.
If I didn’t give enough info, let me know. Thanks in advance for suggestions.
There’s not really enough info here. What’s NOT allowed seems to make sense, but we’d need to have a better idea of what IS allowed in order to suggest a real solution. The previous response, for example, assumes that there must be precisely 4 digits in the value, but misses the fact that the user might choose to enter 1000.0001.
What is the field for? Would fractions (decimals) make sense at all?
Sorry if I didn’t give enough info. The field is actually very simple and will contain building height in feet – whole numbers only. So, numbers such as 2, 22, 222, 2222 are all allowed.
//expecting a field object, but may get a field name
if (typeof field == "string") {
field = document.forms[0].elements[field];
}
//define min and max values
var MIN_HEIGHT = 6;
//a roomy doghouse, but a cramped shed;
var MAX_HEIGHT = 3000;
//roughly 400 feet taller than the burj dubai;
//remove commas first
field.value = field.value.replace(/\,/g, "");
var val = field.value;
if (val.match(/\D/g)) {
//there is a character other than 0-9
field.value = "";
alert("Some error message");
field.focus();
return false;
}
//try to convert to a number
val = parseInt(val);
if (isNaN(val) || val < MIN_HEIGHT || val > MAX_HEIGHT) {
//bad value
field.value = "";
alert("Some other error message");
field.focus();
return false;
}
return true;
}
Since you are dealing with a real height of a real building, you can use real max and min values. Six feet is really too short even for a regulated outbuilding, and three thousand feet will be a new record (and will give you something on the order of twenty years to change the validation before roofing becomes an issue).