Search code examples
c#validationconsole-applicationdata-annotations

Validate only few properties of a model class using Data Annotations from a Console application in c#


I have a model class with several properties like below and each property have Data Annotations for the validation

Class User{

[Required]
public string First Name{get;set;}

[Required]
public string Last Name {get;set;}

[Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]
public string Email {get;set;}

[Required, MaxLength(20), DataType(DataType.Password), Display(Name ="Password")]
public string Pasword {get;set;}
}

Now, in the Console app I ask user to give me an email address and password to Login. How can I validate if a given email and password satify the conditions. Since it is login, I dont want to validate First Name and Last Name

var context = new ValidationContext(user);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(user, context, results, true);

TryValidateObject takes an instance as a first parameter, so when I do this it also returns me error for First Name and Last Name

Can someone please suggest how can I validate only Email and password using the same User class?


Solution

  • If you have a different part of the app that requires a different set or properties and validation rules, then you should be using a completely distinct model for that purpose. So you could have a new model like this:

    public class UserCredentials
    {
        [Required, EmailAddress, MaxLength(256), Display(Name = "Email Address")]
        public string Email {get;set;}
    
        [Required, MaxLength(20), DataType(DataType.Password), Display(Name ="Password")]
        public string Password {get;set;}
    }
    

    Now your code that looks something like this will work:

    UserCredentials userCredentials = .... //Get the credentials from somewhere
    
    var context = new ValidationContext(userCredentials);
    var results = new List<ValidationResult>();
    
    var isValid = Validator.TryValidateObject(userCredentials, context, results, true);
    

    Also, if you want to share this code with the user class, you could make use of inheritance:

    public class User : UserCredentials
    {
        [Required]
        public string FirstName{ get; set; }
    
        [Required]
        public string LastName { get; set; }
    }