Reputation: 7622
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>
Upvotes: 8
Views: 4368
Reputation: 2221
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"));
}
Upvotes: 1
Reputation: 66641
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.
Upvotes: 2