I have a domain model which has 10 fields in it. I have 5 views with different fields from this model(Each view having a different set of fields). For this purpose, I created a ViewModel for each view(total 5 ViewModels).

My question is in every view model I have to duplicate the validation logic. Is there any simple approach to avoid validation logic duplicating for every ViewModel?

Below is how my models and ViewModels look like.

public class Student {
    public int Id { get; set; }
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    [StringLength(15)]
    [DataType(DataType.PhoneNumber)]
    public string Mobile { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Range(5,12)]
    public int ClassId { get; set; }
    [Range(0,1000)]
    public int MarksObtained { get; set; }
    [DataType(DataType.DateTime)]
    public DateTime DateOfBirth { get; set; }
}


public class StudentDetailsViewModel {
    //validation duplicated for each field
    public int Id { get; set; }
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    [StringLength(15)]
    [DataType(DataType.PhoneNumber)]
    public string Mobile { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [DataType(DataType.DateTime)]
    public DateTime DateOfBirth { get; set; }
}


public class StudentMarksViewModel
{
    //validation duplicated for each field
    public int Id { get; set; }
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    [Range(5, 12)]
    public int ClassId { get; set; }
    [Range(0, 1000)]
    public int MarksObtained { get; set; }
}

So I do not want my validation logic duplicated everywhere. I want a centralized validation logic and my ViewModels to use them without mentioning everywhere.

Related posts

Recent Viewed