PDA

View Full Version : Form field check for specific input



codeparrot
01-14-2011, 11:03 PM
Hello everyone,

I'm currently using the following JavaScript to check for required fields on a contact form:

http://www.dynamicdrive.com/dynamicindex16/requiredcheck.htm

I would like to add an anti-spam feature to this code, where it checks a field name "anti-spam" for a value of "7". See the form code below for details. Is this possible? Thanks in advance!



<form name="formcheck" onsubmit="return formCheck(this);">
First Name: <input type="text" name="first-name"><br />
Last Name: <input type="text" name="last-name"><br />
What is 3+4? <input type="text" name="anti-spam">
<input type=submit value="Submit Form">
</form>

codeparrot
01-15-2011, 05:39 AM
Nevermind, got it!

djr33
01-15-2011, 05:46 AM
It doesn't matter. Not only does that always equal 7, so it would be easy to program a bot to get around it, but if the bot submits directly then it won't ever use your Javascript. In fact, bots don't use Javascript because they (almost) always use direct submissions rather than Javascript, and Javascript certainly won't stop it from submitting.
Since Javascript operates only in the browser, the browser (might be a bot) can ignore it, for example if Javascript is disabled (intentionally?). You would need to use a serverside language like PHP or ASP to stop spam.


Basically that script will help a user to not forget the required fields, but if someone wants to get around it (or has Javascript disabled) it won't be "secure" in any sense.

codeparrot
01-15-2011, 05:56 AM
Just when I got all excited after figuring it out =/



// Start anti-spam feature
var obj = formobj.elements["anti-spam"];
if(obj) {
if(obj.value == "" || obj.value == null) {// Check for empty or null values
alertMsg += "What is 10+5?\n";// Enter field description to appear in dialog box
} else if(obj.value != "15" ) {
alertMsg += "Incorrect value for anti-spam\n";// Enter response for value other than 15
}
} else alert("The anti-spam field was not found");
// End anti-spam feature


What's the appropriate way to do it in PHP?

djr33
01-15-2011, 06:22 AM
Google "CAPTCHA" and start reading. Also "anti spam" + "PHP" might help.

In short, you'll want to check that the field was submitted and that its value is 7. But to create a secure system you'll need to vary that and store that somehow. The way to do this securely (so that a bot can't just read your stored value somewhere in the script) is to use PHP sessions so that you store the expected value when you create it (display the form) then compare that to the submitted value on the next page.