Search code examples
asp.net-mvcunobtrusive-validation

ASP.net MVC Unobtrusive Validation


I'm having trouble validating a form before sending the input to an Azure Logic App. On clicking the submit button in the view, form contents are submitted without validation. Validation does fire but the form is submitted whether valid or not. Can anyone help?

Model...

    public class Contact
{
    [DisplayName("Name:")]
    [Required(ErrorMessage = "Please enter your name.")]
    public string Name { get; set; }

    [DisplayName("Email:")]
    [Required(ErrorMessage = "Please enter your email address.")]
    [RegularExpression(@"^\S+@\S+\.\S+$", ErrorMessage = "Please enter a valid email address.")]
    public string Email { get; set; }

    [DisplayName("Phone:")]
    [MaxLength(15)]
    [MinLength(8)]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "Phone number can only contain numbers.")]
    public string Phone { get; set; }

    [DisplayName("Message:")]
    [Required(ErrorMessage = "Please enter a message.")]
    public string Message { get; set; }

    [DisplayName("newsletterTextbox")]
    [Required(ErrorMessage = "Please enter your email address.")]
    [RegularExpression(@"^\S+@\S+\.\S+$", ErrorMessage = "Please enter a valid email address.")]
    public string newsletterTextbox { get; set; }
}

View...

<div class="col-md-8 col-md-push-1">
            <!-- CONTACT FORM -->
            <div id="contactDiv" class="contact-form">
                <form id="contactForm">
                    <div class="form-group">
                        @Html.TextBoxFor(x => x.Name, new { placeholder = "Name", @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.Name, "", new { @style = "color: Orange" })
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(x => x.Email, new { placeholder = "Email", @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.Email, "", new { @style = "color: Orange" })
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(x => x.Phone, new { placeholder = "Phone", @class = "form-control" })
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(x => x.Message, new { placeholder = "Message", @class = "form-control" })
                        @Html.ValidationMessageFor(x => x.Message, "", new { @style = "color: Orange" })
                    </div>
                    <button type="submit" id="submit" onclick="contactSubmit()" name="submit" class="btn btn-primary btn-lg text-center float-right">Submit your message</button>
                </form>
            </div>
            <!-- / CONTACT FORM -->
        </div>

js...

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/superagent/2.2.0/superagent.min.js"></script>

@Scripts.Render("~/bundles/jquery");
@Scripts.Render("~/bundles/jqueryval");

<script type="text/javascript">
$(document).ready(function () {
    var frm = $("#contactForm");
    frm.validate();
});

function contactSubmit() {
    var f = $("#contactForm");
    if (f.valid()) {
        superagent
            .post(*** Azure Logic App URL ***)
            .send({
                name: document.getElementById('Name').value,
                email: document.getElementById('Email').value,
                phone: document.getElementById('Phone').value,
                message: document.getElementById('Message').value
            })
            .end(function (err, res) {
                if (err || !res.ok) {
                    alert('Whoops. Something went wrong.');
                } else {
                    var div = document.getElementById('contactDiv');
                    var successText = document.getElementById('contactText');
                    div.style.display = "none";
                    successText.Text = "Thanks! We'll be in touch";
                    successText.innerHTML = "Thanks! We'll be in touch";
                    successText.value = "Thanks! We'll be in touch";
                }
            });
        return false;
    }

    else {
        return false;
    }

}
</script>

Solution

  • Wrap your form with

    @using (Ajax.BeginForm("ActionName", new { Controller = "ControllerName", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessFunction", HttpMethod = "POST", UpdateTargetId = "idtobeupdated"}, new { id = "idofform" }))
    

    and don´t use javascript / jquery.

    You need to install Microsoft.jQuery.Unobtrusive.Validation and *.Ajax for this.