PDA

View Full Version : Validation script gone awry



Oahgneg
May 7th, 2008, 07:55 PM
I am trying to use a javascript to do validation for a textbox "Cname" & a dropdown list "country":



<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false;}
else {return true}
}
}function validate_form(thisform)
{
var myindex=country.selectedIndex;
with (thisform)
{
if (myindex==0) {
alert("Please select your country");
country.focus;return false;
}
if (validate_required(Cname,"Please type in your name")==false)
{name.focus;return false;}
}
}
</script>

with this:


<html>
<head>
<title>Test</title>
</head>
<BODY>
<form action="insert.php" onsubmit="return validate_form(this)" method="post">

<table style="width: 100%;" class="style1" border="0"
cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="width: 176px;">
<p>Name : </p>
</td>
<td>
<p><input name="Cname" size="33"
maxlength="32" id="Cname" type="text" /></p>
</td>
</tr>
<tr>
<td>
<p>Country : </p>
</td>
<td>
<p>
<select name="country" id="country"
style="width: 300px;">
<option value="0" selected="selected">Please
Choose Your Country</option>
<option value="1">Australia</option>
<option value="2">United States</option>
</select>
</p>
</td>
</tr>
</tbody>
</table>
</form>
</BODY>
</HTML>

Is there a syntax error? Because I got "Duplicate entry '' for key 1".

shyam
May 8th, 2008, 04:43 PM
I am trying to use a javascript to do validation for a textbox "Cname" & a dropdown list "country":



<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false;}
else {return true}
}
}function validate_form(thisform)
{
var myindex=country.selectedIndex;
with (thisform)
{
if (myindex==0) {
alert("Please select your country");
country.focus;return false;
}
if (validate_required(Cname,"Please type in your name")==false)
{name.focus;return false;}
}
}
</script>

Is there a syntax error? Because I got "Duplicate entry '' for key 1".

why the block highlighted in red inside the with block? in javascript all function invocations must be terminated with () even if they have no arguments so, name.focus is as good as a comment :/. The valid values of selectedIndex begin from 0 if nothing is selected its -1