PDA

View Full Version : JavaScript form validation woes



thegoose
08-04-2009, 09:48 PM
Desperately seeking help with a little script. I'm useless with JS :confused:
This is the last function in my script. Anyone know why it would not throw up the error when the radio box with name 'method' and value 'fax' is checked and the input with name 'vetfax' is empty?


function DoCustomValidation()
{
var frm = document.forms["request"];
if(frm.method.value=="fax" && frm.vetfax.value=="")
{
sfm_show_error_msg('Please provide a fax number');
return false;
}
else
{
return true;
}
}

rainarts
08-05-2009, 01:03 AM
Hi thegoose,

try this simple variation:


var DoCustomValidate = function() {
var frm = request || document.forms.request;
if ( frm.method.value !== "fax" && frm.method.value ) {
return true;
} alert("Please provide a fax number");
return false;
};

thegoose
08-05-2009, 07:46 AM
Thanks rainarts. That didn't work. There must be something somewhere else that's broken too. Appreciate the help.

vwphillips
08-05-2009, 10:20 AM
just guessing without seeing your page but


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
/*<![CDATA[*/
function DoCustomValidation(){
var pass=true,frm=document.forms["request"],rads=frm.method
for (var z0=0;z0<rads.length;z0++){
if (rads[z0].checked&&frm['vet'+rads[z0].value].value.replace(/\s/g,'').length==0){
alert('Please provide a '+rads[z0].value+' number');
pass=false;
}
}
return pass;
}


/*]]>*/
</script></head>

<body>
<form name="request" >
Fax <input type="radio" name="method" value="fax" /><input name="vetfax" /><br />
Post <input type="radio" name="method" value="post" /><input name="vetpost" /><br />
<input type="button" name="" value="TEST" onclick="DoCustomValidation()"/>
</form>
</body>

</html>

prasanthmj
08-05-2009, 11:06 AM
To check whether the radio button with the given value is selected, you have to loop through the radio buttons like this:


if(objRadio.length)
{
for(var c=0;c < objRadio.length;c++)
{
if(objRadio[c].checked == "1" &&
objRadio[c].value == value)
{
return true;
}
}
}
else
{
if(objRadio.checked == "1" )
{
return true;
}
}


I guess you are using the JavaScript Form Validation script here (http://www.javascript-coder.com/html-form/javascript-form-validation.phtml).

There is a fourth parameter for the addValidation() function.
The fourth parameter is the condition in which the validation should trigger.

Try:
myformValidator.addValidation("vetfax","req","Please fill in vetfax","VWZ_IsChecked(document.myform.elements[\"method\"],\"fax\")");