Javascript Validation

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.

Subject: Javascript Validation

You can do all the validation in jscript. Make sure its a number > 999 and < 10000.

Enter a hidden field at the top of the form computed to @ISNewDoc. That should get you going.

Subject: Javascript Validation

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?

Subject: RE: Javascript Validation

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.

Subject: RE: Javascript Validation

This should cover it:

function validateHeight(field) {

//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).

Subject: RE: Javascript Validation

Thank you so much. I’ll try this today.

Do you think I could wrap my new document check around the call in the onchange of the field? Such as:

if(document.forms[0].IsNewDoc.value == ‘NewDoc’ {

return validateHeight(this.value)

}

That way, it will only call this on new documents.

Subject: RE: Javascript Validation

You sure can.

Subject: RE: Javascript Validation

Thanks Stan – it works great!