1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.