I'm developing a contact form in MVC 6 and I'm using Google reCaptcha v2 for authentication and form is submitting through Ajax. All I want is How do I validate the reCaptcha Control? It is working fine but I'm not finding any validation like that of Model Validation or jQuery validation. Can Anyone show me that how do I validate it on Client-Side or Server-Side both will be recommended.
Here is my code
HomeController:
[HttpPost]
public IActionResult Contact(ContactViewModel model)
{
string EncodedResponse = Request.Form["captchaResponse"];
bool IsCaptchaValid = (CaptchaResponse.Validate(EncodedResponse)); // it is working and returns true if I check the reCaptcha with Google Server.
if (IsCaptchaValid)
{
}
return View();
}
View:
<form name="sentMessage" asp-controller="Home" asp-action="Contact" id="contactForm" novalidate method="post">
<div class="row control-group">
<div class="font-light form-group col-xs-12 floating-label-form-group controls">
<div class="g-recaptcha" data-sitekey="6LdKRxQTAAAAAHd9kNw8qp4OyxfWxvLnAhxVr8mu"></div>
<br />
<span class="text-danger" id="ValidMessage"></span> <!--Here I want to display validation messge-->
</div>
</div>
<br />
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
and here is my JavaScript file:
$.ajax({
url: "/Home/Contact",
type: "POST",
data: {
name: name,
subject: subject,
email: email,
message: message,
captcharesponse: captchaResponse
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})