validation-summary-errors div showing even if there is no error binded to a property

I'm working on a change password form when I encountered this strange behavior from mvc3. I created a simple form and change password model with 3 fields (old, new, confirm password). Then I extended ValidationAttribute to validate the password's length. ValidatePasswordLengthAttribute
public class ValidatePasswordLengthAttribute : ValidationAttribute
    {
        private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, _minCharacters);
        }

        public override bool IsValid(object value)
        {
            var valueAsString = value as string;
            return (valueAsString != null && valueAsString.Length >= _minCharacters);
        }
    }
Then on my form, I'm showing the error as: Field errors beside the field and page errors below. For the readers information field and page error can be added by:
//Field Error
ModelState.AddModelError("Password", "Field Error(Password)");
//Page Error
ModelState.AddModelError(string.Empty, "Page Error");
Note that I've styled my validation-summary-errors div with red background. On form submit, I'm surprised to see a red div but with no content, a bug? So my solution is to simply check if there are visible li element under validation-summary-errors. Because after I submit it's css property display=none. Solution:
<script type="text/javascript">
        //work around to the validation summary bug
        $(document).ready(function () {
            if ($(".validation-summary-errors li:visible").length == 0) {
                $(".validation-summary-errors").hide();
            }
        });
    </script>
validation-summary-errors div showing even if there is no error binded to a property validation-summary-errors div showing even if there is no error binded to a property Reviewed by Edward Legaspi on Wednesday, December 28, 2011 Rating: 5

No comments:

Powered by Blogger.