5

I'm using server validation and want to change the element class when invalid. So for example I have a textbox with a validationmessage:

@Html.ValidationMessageFor(m => m.FirstName, new {@class = "error"})
@Html.TextBoxFor(m => m.FirstName, new {@class = "aftererror"})

When the textbox data is invalid I want the textbox to get a red border. I tried to change it using css selectors:

 .error + .aftererror
    {   
        border:solid 1px red;
        }

so when the validationmessage is showing, the textbox would get the "aftererror" class. Unfortunately the validation element is also showing even if the data is valid, only there is no text.

So how would I change the css class of the texbox on error, or have the validation element disappear when there's no error.

3 Answers 3

12

This is already built into ASP.NET MVC.

Take a read through Scott Gu's blog post on MVC Validation.

Basically the framework is setup to automagically add a input-validation-error css class to invalid fields.

Here's the CSS I use to add the red border and pinkish background (it's DotLess so not exactly what the CSS will look like)

.field-validation-error
{
    color: @valid-dark;
}

.field-validation-valid
{
    display: none;
}

input.input-validation-error,
textarea.input-validation-error,
select.input-validation-error
{
    border: 1px solid @valid-dark ;
    background-color: @valid-light;
    font-size:100%;
}

.validation-summary-errors
{
    font-weight: bold;
    color: @valid-dark;
    ul{
        display: none;
    }
}

.validation-summary-valid
{
    display: none;
}

just make sure you also have the jquery.validate.unobtrusive.js added to your page. It helps with all the validation goodness

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

3 Comments

The problem is that the .field-validation-.. classes are not being added to my textbox. I figured out this is because I'm validating a property, and the ModelError doesn't map to the textbox.
Your property is called FirstName. So you need to create a buddy class to that property and add the validation logic. Then it will be applied all the way down the line.
Is there a way to add another class except the default .field-validation-error etc.?
4

In MVC4 it is:

.input-validation-error
{
     border: 1px solid red !important;
}

Comments

0

The .field-validation classes will apply to properties, but are likely being overridden, probably by

input[type="text"] 

Set the styles of .input-validation-error (NOT .field-validation-error) to !important or get rid of input[type="text"] from the stylesheet.

Comments

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.