How to make Recaptcha a required field in MVC 3?

I have an answer to my registration form. The user must enter something in the recaptcha field before he is sent 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; } 

When loading, I see the message "captcha required". But if I print something, it still appears. The form is sent with an empty recaptcha box.

How can I do the required recaptcha field on the client side?

thanks for the help

EDIT: I added this to catch the submit btn click event, but does not stop sending 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> 
+6
source share
2 answers

so that it works when you enter it, return a value, not just call it. A type

 onsubmit="return ValidateAndSubmit();" 

or

 onclick="return ValidateAndSubmit();" 

You can also try adding the same validation to the form tag.

+2
source

Although this question is quite old, I thought it could help share my solution that supports unobtrusive javascript MVC.

 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")); } 
+1
source

Source: https://habr.com/ru/post/891047/


All Articles