no

How to Fix Summary Error Display in C#

I'm working on a change password form when I encountered this strange behavior from mvc3. I created a simple form and change password mo...

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>

Related

c# 9159809378094243408

Post a Comment Default Comments

item