1

I am adding Required attribute on a list property using a solution in the following stack overflow answer:

Required Attribute on Generic List Property

[AttributeUsage(AttributeTargets.Property)]
public sealed class CannotBeEmptyAttribute : ValidationAttribute
{
    private const string defaultError = "'{0}' must have at least one element.";
    public CannotBeEmptyAttribute ( ) : base(defaultError) //
    { 
    }

    public override bool IsValid ( object value )
    {
      IList list = value as IList;
      return ( list != null && list.Count > 0 );
    }

    public override string FormatErrorMessage ( string name )
    {
        return String.Format(this.ErrorMessageString, name);
    }
}

How would I turn this into client side validation to be used by jquery.validate.unobtrusive ?

Community
  • 1
  • 1
Jonno
  • 181
  • 2
  • 12
  • You cannot. Client side validation works on properties of your model which are value types and for which you generate corresponding form controls. You don't generate a form control for the collection, just for properties of items in the collection. You could however handle the forms `.submit()` event, check if there are any associated controls for items in the collection, then cancel the submit and display an error message if not. –  Oct 02 '15 at 00:31

0 Answers0