4

I have the following form:

<form action="~/buy-online" method="get" class="buy-online-form clearfix" autocomplete="off" id="buy-online-search">
    <div class="infield-holder clearfix">
        @Html.LabelFor(m => m.CustomerPostcode, new { @class = "infield" })
        @Html.TextBoxFor(m => m.CustomerPostcode, new { @class = "textbox" })
        <input type="submit" value="Buy Online" id="find-retailer-button" class="button" />
    </div>
</form>

@Html.ValidationMessageFor(m => m.CustomerPostcode)

Which works fine and will display an error message when submitted without jQuery, but when I add the jQuery validate scripts (v 1.11.1):

<script src="/scripts/jquery.validate.js"></script>
<script src="/scripts/jquery.validate.unobtrusive.js"></script>

It stops the form submitting but doesn't display the error message

My property is marked like so:

[DisplayName("Enter your full postcode")]
[Required(ErrorMessage = "Please enter your full postcode")]
public string CustomerPostcode { get; set; }

And the html renders like this:

<input class="textbox" data-val="true" data-val-required="Please enter your full postcode" id="CustomerPostcode" name="CustomerPostcode" type="text" value="" />

<span class="field-validation-valid" data-valmsg-for="CustomerPostcode" data-valmsg-replace="true"></span>

If I inspect the input when I hit submit it is adding the class input-validation-error to the textbox but just not updating the validation message.

All the posts that I have checked on this problem just say to include the scripts so I'm at a loss as to why the message is not showing.

I've even tried adding the jquery.unobtrusive-ajax.js script but that didn't seem to do anything either. Any help would be appreciated, thanks.

4
  • 3
    Put the @Html.ValidationMessageFor(..) inside the form tags Commented Oct 31, 2014 at 12:03
  • Ah so simple! It was outside for styling issues but I can change that. If you would like to put that as an answer I'll accept. Thanks! Commented Oct 31, 2014 at 12:17
  • Anyone care to explain the downvote? This is a well formed question about a problem showing enough code to replicate the problem and follows all the rules about what SO is for Commented Oct 31, 2014 at 12:25
  • 2
    Agreed, and cancelled it out. Commented Oct 31, 2014 at 12:27

1 Answer 1

4

You need to include the @Html.ValidationMessageFor(m => m.CustomerPostcode) within the form tags for jquery.validate.unobtrusive to work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.