Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Recaptcha a required field in MVC 3?

I have recaptcha on my signup form. The user must type something in the recaptcha box before it gets posted to the server. I have server side validation and client side validation for other fields.

Generated html from rcaptcha:

<input type="text" id="recaptcha_response_field" name="recaptcha_response_field" autocomplete="off" class="valid">

View:

@ReCaptcha.GetHtml(theme: "red", publicKey: GetPublicKey())
@Html.ValidationMessageFor(m => m.recaptcha_response_field)

Model:

[Required(ErrorMessage = "'captcha required' ")]
public string recaptcha_response_field { get; set; }

On load I see the 'captcha required' message. But if I type something it still appears. The form gets submitted with empty recaptcha box.

How can I make recaptcha required field at client side?

Thanks for helping

EDIT: I added this to intercept the submit btn click event, but it doesn't stop from posting the form.

    <button type="submit" id="btnSubmit" class="sprt bg_red bt_red h25" onsubmit="ValidateAndSubmit();">Signup</button>
<script type="text/javascript">    
    function ValidateAndSubmit() {
            var v=$('#recaptcha_response_field').val();
            if (v == '' || v == undefined) {
                alert('captcha is required');
                return false;
            }
            return true;
        }
</script>
like image 694
kheya Avatar asked Jun 21 '11 18:06

kheya


People also ask

How do you make a Captcha required in HTML?

HTML CAPTCHA Code<input id="textBox" type="text" name="text"> - This element is used to create an input box to type the CAPTCHA. <input id="submitButton" type="submit">: This button submits the form and checks whether the CAPTCHA and the typed text are the same.


2 Answers

to make it work as you type it, return the value, not just call it. Type

onsubmit="return ValidateAndSubmit();"

or

onclick="return ValidateAndSubmit();"

Also you can try to add the same validation on the form tag.

like image 82
Aristos Avatar answered Nov 06 '22 09:11

Aristos


Though this question is pretty old, thought it it might help to share my solution, that supports MVC unobtrusive javascript.

if ($("#recaptcha_response_field").length > 0) {
  $("#recaptcha_response_field").attr("data-val", "true")
    .attr("data-val-required", "The captcha field is required.");
  $("<span />")
    .attr("data-valmsg-replace", "true")
    .attr("data-valmsg-for", "recaptcha_response_field")
    .addClass("field-validation-valid")
    .appendTo($("#recaptcha_response_field").parents(".editor-field"));
}
like image 40
OzB Avatar answered Nov 06 '22 09:11

OzB