PDA

View Full Version : javascript form validation


hackedminds
03-23-2005, 03:31 PM
Hi there,

I'm making a form, and a javascript file to validate it. It uses onchange to display a message beside the input field if there is an error.

Here is the input field HTML code:
Line 20:<table id="form"><form name="gofrance_form" onsubmit="return validate_form(this)" action="confirmation.html">
Line 21:<tr><td><strong>Username:</strong></td><td><input type="text" name="username" maxlength="16" onchange="validate_username(this, 'usernamemsg');"/></td><td id="usernamemsg">&nbsp;</td></tr>

Here is the javascript function to validate the field:
function validate_username(fieldName, errmsgID)
{
currentFieldLength = fieldName.maxLength; currentField = new String(fieldName.name); for (i=0;i<=currentFieldLength;i++)
{
if (Pseudo:character isnt alphanumeric)
{
errorcount++;
errorMessage="Invalid text" display_message(errmsgID,errorMessage); fieldName.focus();
}
}
}

Here is the javascript function to display the message
function display_message(errmsgID, errmsg)
{
document.getElementById(errmsgID).firstChild.nodeValue=errmsg;
}

There is obviously more code for the other input fields etc, but these are "in my mind" the relevant ones needed to examine the error.

The error
When I type a string into the input field and then lose focus of the input field, I get an object expected error Line 21, Char 1 (This is the HTML code above for the table row with input field)

The form can be viewed at: http://www.hackedminds.co.uk/gofrance/pages/memberregistration.ht ml

The javascript file can be viewed at:
http://www.hackedminds.co.uk/gofrance/scripts/workingvalidation.txt

I hope someone can shed some light on this problem for me please! Any help would be much appreciated!

Paul

Jon Hanlon
03-23-2005, 04:51 PM
This line is pseudocode, not javascript:
if (Pseudo:character isnt alphanumeric)

Rip out the validate_username function and replace it with:

function validate_username(fieldName, errmsgID) {
var alphaTest = /(^[a-z]|\s)*$/i; // alpha or space
if (!alphaTest.test(fieldName.value)) {
errorcount++;
errorMessage="Invalid text";
display_message(errmsgID,errorMessage);
fieldName.focus();
}
}

hackedminds
03-23-2005, 05:40 PM
Hi Jon,
Thanks for your reply. I know that line is pseudocode - i just had it in the post because my expression for checking alphanumeric was too long winded to put into a post, but i will try your short hand version!

Thanks again!

Paul