Validation in .NET

For validating a simple class, you can add [Required] ( see https://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx

But how to validate same object depending on his state? For example, when it is new, the email is required. But after saving, the user mus also add FirstName( also think about workflows)

There is a simple solution in .NET : IValidatableObject
In this example , I validate differently based on the object is new or retrieved from database:

 internal class Person:IValidatableObject
    {
        public int id { get; set; }
      
        public string Email { get; set; }

        public string FirstName { get; set; }

        /// <summary>
        /// MVC and EF are calling this if the class implements  IValidatableObject
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if (string.IsNullOrWhiteSpace(Email))
            {
                yield return new ValidationResult("my Email is required");
            }
            if (id == 0) //new
            {
                yield break;
            }

            //existing
            if(string.IsNullOrWhiteSpace(FirstName))
            {
                yield return new ValidationResult("First name is required");
            }

        }
    }

If you want to see in action , please see https://youtu.be/rjj0jjj3rxM