MVC 2 Client Side validation messages are showing on page load

by Donovan Brown 19. December 2010 20:33

Problem

When I enable Client side Validation on my MVC 2 view the validation error messages are showing as soon as the page loads even if everything is valid.

Solution

Define the styles to hide content until an error is detected.

Code

/*----------------------------------------------------------
ASP.NET MVC FRAMEWORK DEFAULT CSS CLASS NAMES
----------------------------------------------------------*/
.error,.field-validation-error{color:red}

.input-validation-valid,.field-validation-valid,.validation-summary-valid{display:none}
.input-validation-error{background-color:#fee;border:1px solid red; outline: none}
.input-validation-error:focus{outline:none}
input[type="text"].input-validation-error:focus, select.input-validation-error:focus{outline:none}

.validation-summary-errors{color:red}
.validation-summary-errors span{font-weight:700}
.validation-summary-errors ul{list-style:disc inside}
.validation-summary-errors ul li{font-weight:normal}
.validation-summary-errors ul li label, .validation-summary-errors ul li span{display:inline !important; font-weight:normal}

Explanation

When you enable client side validation the content of the error messages and validation summary are rendered to the screen with a class of *-valid. The class is changed to *-errors when a validation error is detected.  If your style sheets does not hide the *-valid style sheet classes you will see that content when the page is display.

Tags: , ,

Work

About the author

My name is Donovan Brown and I am a Technology Specialist for DevTools with Microsoft with a background in application development.  I also run one of the Nation’s fastest growing online registration sites for motorsports events DLBRacing.com.  When I am not writing software I race cars for fun.  DLBRacing.com has given me the opportunity to combine my two passions writing software and racing cars.

AdSense

Month List

AdSense