Extending the awesome answer by Peter Kiss
You will setup a base class without annotations, then create subclasses with unique requirements. Consider the following:
public class UserModel
{
public int ID { get; set; }
public virtual string FirstName { get; set; } // Notice the virtual?
public string LastName { get; set; }
}
// Used for creating a new user.
public class InsertUserModel : UserModel
{
[Required]
public override string FirstName { get; set; } // Notice the override?
}
// Used for updating a user.
public class UpdateModel : UserModel
{
// Custom validation
[FirstNameUnique("This name is already taken.")]
public override string FirstName { get; set; }
}
Important
You must decorate your base-properties with virtual
modifier, indicating that it can be overridden (or replaced) in the subclasses. Then in the subclasses, properties that will replace your existing properties must be decorated with override
modifier.
Custom Validation
using System.ComponentModel.DataAnnotations;
public class FirstNameUniqueAttribute : ValidationAttribute
{
public FirstNameUniqueAttribute(string errorMessage)
{
this.ErrorMessage = errorMessage;
}
public override bool IsValid(object value)
{
string firstName = value as string;
// This condition is for properties with validations
// but not required. Kinda like [StringLength], with
// validation but not required.
if (string.IsNullOrEmpty(firstName))
{
return true;
}
// Put validation logic here.
return valid;
}
}