I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:
public class Instrument : BaseObject
{
public int Id { get
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
///
/// Error message for Minimum password
///
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
///
/// Minimum acceptable password length
///
public const int PasswordMinimumLength = 8;
///
/// Gets or sets the password provided by the user.
///
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
///
/// Only need to validate the minimum length
///
/// ValidationContext, ignored
/// List of validation errors
public IEnumerable Validate(ValidationContext validationContext)
{
var errorList = new List();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
Must contain: 8 characters, 1 upper-case, 1 lower-case
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
The Password should be a minimum of 8 characters long.
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!