Forum Moderators: open
I have this form validating but if you put in empty spaces into a field it thinks it has value and passes the value. How can I stop this?
Thanks Chris
Snippet of code
<form name="ws_form" method="post" action="blankform.php?form=6" onsubmit="return formCheck(this);" target="forms">
function formCheck(formobj){
var fieldRequired = Array(
"ins_name",
"suburb");
var fieldDescription = Array(
"Name of Person or Company seeking insurance",
"Suburb/Town");
var alertMsg = "Please complete the following fields:\n";
var l_Msg = alertMsg.length;
for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired[i]];
if (obj){
switch(obj.type){
case "select-one":
if (obj.selectedIndex == -1 ¦¦ obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "text":
case "textarea":
if (obj.value == "" ¦¦ obj.value == null){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
default:
}
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
}
}
if (!blnchecked){
alertMsg += " - " + fieldDescription[i] + "\n";
}
}
}
}
if (alertMsg.length == l_Msg)
{
NewWindow('blankform.php?form=6','forms','820','530','YES','NO');
return true;
}else{
alert(alertMsg);
return false;
}
}
if( obj.value == "" ) Trim the input value of leading & trailing whitespace before testing.
To make this neater, you can create a custom String method (place this at the top of the script - not in the function itself)
String.prototype.trim = function(){ return this.replace( /^\s+¦\s+$/g, "") }
....
if( obj.value.trim() == "" )