Search code examples
validationasp.net-coreasp.net-identity

How do I annotate the Identity user's email property?


If I have a Customer model, that extends IdentityUser, then I can annotate the properties I add easily...

public class Customer : IdentityUser {
  [Required]
  public string Mobile { get; set; }
  // Other properties omitted for clarity
}

If I then had a <form> to enable the customer to update their details, I would not have to do any validation on their mobile number (taking the simple assumption that any non-empty string is OK for this example), as the framework would do it for me.

How do I do this if I want to annotate any of the Identity properties, such as Email? These properties don't appear in my Customer class, as they come from the base IdentityUser class.

Anyone able to help? Thanks


Solution

  • How do I do this if I want to annotate any of the Identity properties, such as Email? These properties don't appear in my Customer class, as they come from the base IdentityUser class.

    You can override and use data annotations on these properties, like below.

    public class Customer : IdentityUser
    {
        [Required]
        public string Mobile { get; set; }
    
        [StringLength(20)]
        public override string Email { get; set; }
    
        // Other properties omitted for clarity
    }
    

    Besides, you can use fluent API to configure model and override data annotations. For more information, please check this doc: https://learn.microsoft.com/en-us/ef/core/modeling/#use-fluent-api-to-configure-a-model