user1186050 user1186050 - 2 years ago 190
Javascript Question

Using a html.validationmessagefor for a client side error message

I have server side validation messages for some of my text fields. The field 'title' is a required field server side with a '[Required]' data attribute in the class, but this only seems to get checked on a postback or form submit. I'm saving the 'title' text field on a jquery .change event, sudo code below. But I want to use my validationmessagefor to show the error message from the client side check. Not sure how to go about doing this?


@Html.ValidationMessageFor(model => model.Overview.Title, "", new { @class = "text-danger" })

rendered as

<span class="field-validation-valid text-danger" data-valmsg-for="Overview.Title" data-valmsg-replace="true"></span>

If I want to do some client side checking in javascript and then use this element to display a client side error message can I do so. I'm just trying to save myself of using another hidden element. I know I would have to use


because the other data attributes are the same for all the other text fields.

Whats the best way to do display client side error messages here if I want to check to make sure the "title" has length greater then 1?

Maybe something like -

$('#Overview_Title').change(function() {
var title = $(this).val();
if (title.length == 0) {
// show error message "title has to be a value to save"
else {
// do other work like save to db

Answer Source

You've got a few ways to do this but I'd argue that this is the easiest way:

MVC will by default bundle the jquery.validate javascript library into your page. Since you are already marking the field with the [Required] attribute, the Html.EditorFor will bind the correct attributes into your HTML for you so that validation can happen as necessary.

To make your current logic work with the smallest changes, you could add a <form> tag around your input field(s). I think you need this for the validate method to work out of the box. Then your javascript would change to something like this:

$('#Overview_Title').change(function() {
if ($(this).valid()) {
  // do your stuff
else {
  // error message displayed automatically. don't need to do anything here unless you want to

This would allow you to use the Required attribute to set your error message text and your ValidationMessageFor should display the error message without any extra effort on your part.

Check out this plunkr as a proof of concept:


I'm not positive I understand your follow-up question. But if you wanted to add a rule to a field dynamically, you could do something along these lines:

$( "#someinput" ).rules( "add", {
 required: true,
 messages: {
 required: "a value is required to save changes"

You could add rules that aren't reflected server side by doing something like this. Then you could validate that input in the same way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download