1

I'm having trouble with my ASP.NET MVC 2 form validation and setting my style.

Here is an example of my form, with a validation error:

alt text

The field uses the following html:

<div class="registration-field">
     <label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
     <%= Html.ValidationMessageFor(x => x.FullName)%>
</div>    

The problem is, to show the highlight across the entire element, I need to add the CSS class "registration-field-error" to the first div.

<div class="registration-field registration-field-error">
     <label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
     <%= Html.ValidationMessageFor(x => x.FullName)%>
</div>    

The CSS for registration-field-error is:

.registration-field-error
{
    background-image:url(../Content/Images/box-background-error.png);
    background-repeat:repeat-y; 
}

I can do some complicated logic to check the ViewState for errors, which works fine for server validation errors, but not for client-side validation:

<% if (ViewData.ModelState["FullName"] == null) { %>
     <div class="registration-field">
<% }  else { %>
     <div class="registration-field registration-field-error">
<% } %>

My first thought was to make a new Html helper to decide if it should use the registration-field-error class:

<%= Html.FormFieldFor(x => x.FullName, ViewData.ModelState) %> 

And then editing the MicrosoftMvc.Ajax.js script to add the class when it detects clientside validation errors.

Or, is there a better way to accomplish this?

1 Answer 1

2

First wrap your div elements without any conditional logic but wrap your Validation Messages in span with class name "error" like below:

<div class="registration-field">      
  <label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>      
    <span class="error"><%= Html.ValidationMessageFor(x => x.FullName)%></span>
</div> 

and then use a function given below to dynamically add the error classes:

$(function(){
 $("div span.error").each(function(){
  var className = $(this).parent().attr("class") + "-error";
  if($(this).html().length > 1)
   $(this).parent().addClass(className);
 });
});

This would be changing less parts of your code.

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

2 Comments

Thanks, that worked great. I think there's a typo above though, with the line if ($(this).html().length < 1). I think it should be length > 1?
If you're using client-side validation, you should update this. Must be easy - probably, the easiest way is to execute nearly the same code each X miliseconds + add the code removing registration-field-error class when validation error class is removed from child div / span.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.