0

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'>&times;")
                    .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'>&times;")
                    .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");
            },
        })
Janshair Khan
  • 2,577
  • 4
  • 20
  • 44
  • This blog post help you: http://venkatbaggu.com/google-recaptcha-asp-net-mvc/ – jpgrassi Jan 02 '16 at 17:31
  • Thanks. Actually I've seen this post several times. But couldn't get through. All I want is to display only a validation message according to above given scenario. – Janshair Khan Jan 02 '16 at 17:39

1 Answers1

0

The problem was with Ajax call. For client-side validation, we just need to update Ajax code as:-

JavaScript

if (captchaResponse == '') {
            $('#captchaCheck').html('Please verify that you are not a robot!');
        }
        else {
            $.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'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent. </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
                $('#captchaCheck').hide();
            },
            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'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding or you may not verify that you are a human. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
                $('#captchaCheck').hide();
            },
        })
        }

and for Server-Side validation, we just need to add a HTTP response in the POST action as:-

if (IsCaptchaValid)
        {
            //await _mailService.SendEmailAsync();
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return View(model);
        }

It solved my problem.

Janshair Khan
  • 2,577
  • 4
  • 20
  • 44