View Full Version : Need javascript to check form field for only 1 character & submit form if present?

Jun 15th, 2012, 05:27 PM
I am trying to use javascript to validate a contact form. I already have it checking if a hidden field is left blank and only submitting the form if it has. I also have it checking if a check box has been unchecked and only submitting the form if it has. As an extra anti-spam bot device I want javascript to check that an "x" (upper or lower case) has been placed in a specific form field so that I can ask the user to complete a simple game of tic-tac-toe in order for the form to be submitted. I am very new to javascript and cannot find anywhere to tell me how to do this.

Jun 15th, 2012, 05:41 PM
var thisField = document.getElementById("fieldname");
var pattern = /x/i; // i = case insensitive
if(pattern.test(thisField.value)) {
// the x or X is in the field value

Jun 16th, 2012, 01:29 AM
I've copied this into my javascript file and changed the field name to match my html but this just submits the form whatever is entered in the field. Am I missing something else that needs changing?

Jun 16th, 2012, 09:08 AM
No, can't get that working either. And now I've managed to lose my original code that worked - my fault for not saving it somewhere first, but I am on the verge of giving up and going back to just not having a contact form.

But if this is for a real life application, you must do the validation in your server side script as well because javascript on it's own is virtually useless in protecting against spam.

People can send data directly to your server side script (as GET or POST) without even opening your form page and so it won't even matter if they have javascript enabled or not.

Do what? I am so much a newbe at this!