Forum Moderators: open

Message Too Old, No Replies

How to check for empty spaces in fields

Checking if empty spaces in fields

         

chrisinoz

7:11 am on Aug 31, 2005 (gmt 0)

10+ Year Member



Hi

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;
}
}

Bernard Marx

8:19 am on Aug 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You're currently testing for a blank input like this (for instance):

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() == "" )

chrisinoz

8:43 am on Aug 31, 2005 (gmt 0)

10+ Year Member



Thanks Bernard

I shall work with that and see how it goes

Cheers

Chris