View Full Version : Dynamic Field Validation
Bobba Buoy
11-24-2004, 10:02 AM
I have a series of inputs that are created at run time dynamically via asp based on the contents of a database. When the form is submitted I want to make sure that all data is numeric. I want to use the following type of structure:
function checkFields() {
if (isNaN(document.update_info.m_awds_x.value))
{
alert('All fields must be numeric values');
return false
}
else
return true
}
Here is the problem: I want a loop to go through the all of the inputs named m_awds_x (where x is a unique identifier from the database). I can write for loops but I don't know how to find the 'end' of the loop in javascript.
I would appreciate any help!!!!
Thanks
RichB
12-23-2004, 02:59 AM
I know this is late, but I just joined and thought maybe you still were interested in it or someone else would be in the future.
When you say that the form is generated dynamically, I'm assuming that you mean you don't know the number of fields to be checked in advance.
I think the simplest thing to do would be to loop through all the elements in the form and check those with the common substring "m_awds_" to see if they're numeric and not empty.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
.error {background: pink}
</style>
<script type="text/javascript">
<!--
function checkFields() {
var i, f = document.update_info;
var submitting = true;
// loop through all form elements
for(i = 0; i < f.elements.length; i++) {
//check only those with "m_awds_" in name
if(f.elements[i].name.indexOf("m_awds_")>=0) {
// if not a number or empty field
if(isNaN(f.elements[i].value) || f.elements[i].value.length==0) {
f.elements[i].className = "error";
submitting = false;
}
else f.elements[i].className = "";
}
}
if(!submitting) {
alert("All fields must be numeric values");
}
return submitting;
}
// -->
</script>
</head>
<body>
<form action="" method="post" name="update_info" onsubmit="return checkFields()">
<input type="text" name="m_awds_1" value="123" /><br />
<input type="text" name="m_awds_2" value="456" /><br />
<input type="text" name="m_awds_3" value="8po" /><br />
<input type="text" name="m_awds_4" value="789" /><br />
<input type="text" name="m_awds_5" value="123" /><br />
<input type="text" name="m_awds_6" value="456" /><br />
<input type="text" name="m_awds_7" value="bleh" /><br />
<input type="text" name="m_awds_8" value="789" /><br />
<input type="text" name="blah" value="not m_awds_ name" /><br /><br />
<input type="submit" />
</form>
</body>
</html>
Any elements like the last one without the substring should be ignored, but the rest should be checked, highlighted with an alert to the user and a flag set to stop the submission.
Bobba Buoy
12-23-2004, 07:18 AM
Thank you very much-yes that is helpful!
vBulletin® v3.6.7, Copyright ©2000-2010, Jelsoft Enterprises Ltd.