Reputation: 3445
I have this custom validation :
[AttributeUsage(AttributeTargets.Property)]
public class CollectionNotEmptyAttribute : ValidationAttribute
{
private const string errorMessage = "'{0}' must have at least one element.";
public CollectionNotEmptyAttribute()
: base(errorMessage)
{
}
public override bool IsValid(object value)
{
var collection = value as ICollection;
if (collection != null)
{
return collection.Count > 0;
}
return false;
}
public override string FormatErrorMessage(string name)
{
return String.Format(this.ErrorMessageString, name);
}
}
My viewmodel
public class ProjectViewModel
{
public ProjectViewModel()
{
this.Users = new Collection<UserProjectViewModel>();
}
public int ProjectID { get; set; }
[CollectionNotEmpty]
public Collection<UserProjectViewModel> Users { get; set; }
}
My View
@Html.ValidationMessageFor(m => m.Users)
The validation is working fine, Model.IsValid
returning false if collection count below 1, but the error message is not showing.
Any help will be appreciated.
Upvotes: 1
Views: 2890
Reputation: 4998
I believe you should override other IsValid
method:
protected virtual ValidationResult IsValid(
Object value,
ValidationContext validationContext
)
since it allows you to return ValidationResult
with proper error message.
The one you overrode just determines whether result is valid or not.
Upvotes: 3