Custom Validation Attribute error message not showing with ValidationMessageFor

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.

Answers


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.


Need Your Help

How to set leading in TextBox?

wpf textbox

I have a TextBox control with some text. I want to modify this: link in that TextBox.

How can I separate variables into an external asciidoc document?

asciidoc asciidoctor

I'm writing a book using asciidoctor. Documents look like this.