简体   繁体   中英

Trying to validate captcha with javascript before sending to php form validation

Hi I'm a relative newbie. Have a mail contact form set up with a captcha image generator. When the captcha is verified, on submitting the form, a php page is actioned which further validates the input data (checking against spam). Challenge: would like to retain form data in case of error in enterred capthca code and needing to return to form. If I use a sticky form with the form sticks okay but I cannot see how I then direct http to the php script for form data validation. So I figure the answer is a javascript function to validate the captcha and stay within the same page where the form appears, ideally just having a pop up message (alert ...) if the enterred code is wrong, before sending the http to the php script page.
I have seen that this can be done but I cannot adapt the code to the captcha I use (ie webspamprotect.com) Could any body suggest a generic js function useable with any captcha ? Would be most grateful for any input. MANY THANKS Steve

It doesn't make sense to be able to validate the CAPTCHA with javascript on the client. If you made it possible to validate with Javascript a scammer could use the validation function to test their guesses before they sent them to the server, so they would always be able to get the answer right.

You could implement an AJAX call requesting the server to validate the attempt instead of requiring a full page refresh, but the validation must still be done on the server.

When the captcha is generated the written word is usually stored inside the session or written into a hidden input field, so it can be validated against the user supplied word, when the form is submitted back to the PHP script.

You could pass the session variable holding this to your JavaScript (or read it from the hidden input if present) when rendering the page holding the form and captcha. Then, when the user clicks submit, intercept the call and check if the entered word matches the expected word.

As for retaining the values: just add the values to your HTML form value attribute. Make sure you escape the output in case users supply malicious code.

EDIT: agreeing with everyone who says you still have to validate the input on the server side as well. Client Side validation can easily be tinkered with and is nothing but a convenience feature for users, so they can fix their input before submitting.

simply check the value of "g-recaptcha-response"

if($('#g-recaptcha-response').val()==''){
 alert('captcha not ticked');
}else{
alert('captcha ticked');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM