ASP.NET MVC 3 Data Annotation: Add validation dynamically

I'm new with data annotation. I'd like to know if it possible (and how) to add some validation dynamically. It is very extensive to explain why, but I've a ViewModel that receives and object when created. In that object I must check for some property and depending its value I should have or not some validations.

An example:

public class ProfileViewModel
{
    [Required(ErrorMessage = "The field {0} is required")]
    [Display(Name = "Client Code")]
    public int ClientCode { get; set; }

    [Required(ErrorMessage = "The field {0} is required")]
    [StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
    [Display(Name = "Company")]
    public string Company { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "LastName")]
    public string LastName { get; set; }

    public ProfileViewModel(User usr)
    {
        if (usuario.ClientCode != null)
        {
            ClientCode = Convert.ToInt32(usr.ClientCode);
        }
        else
        {
             //ClientCode and Company are not yet required.
             //Name and LastName are now required.
        }
        Company = usr.Company;
        Name = usr.Name;
        LastName = usr.LastName;
    }
}
18
задан Mathieu 5 September 2012 в 14:23
поделиться

0 ответов

Другие вопросы по тегам:

Похожие вопросы: