Search code examples
asp.net-mvcdatetimerequired

Datetime required (+18 years)


I have a little problem, here is my code:

public partial class Tourist
    {

        public Tourist()
        {
            Reserve = new HashSet<Reserve>();
        }
        public int touristID { get; set; }

        [Required]
        [StringLength(50)]
        public string touristNAME { get; set; }

        public DateTime touristBIRTHDAY { get; set; }

        [Required]
        [StringLength(50)]
        public string touristEMAIL { get; set; }

        public int touristPHONE { get; set; }

        public virtual ICollection<Reserve> Reserve { get; set; }
    }
}

How can I restrict touristBIRTHDAY to be +18 years old? I think that I have to use this function, but I don't know where to put it: Note: this function it's an example.

DateTime bday = DateTime.Parse(dob_main.Text);
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if(age < 18)
{
    MessageBox.Show("Invalid Birth Day");
}

Thanks ;)

UPDATE: I follow the solution of Berkay Yaylaci, but I'm getting a NullReferenceException. It's seems that my value parameter is default, and then my method is not posting, why? What is the solution to that?


Solution

  • You can write your own Validation. First, create a class.

    I called MinAge.cs

     public class MinAge : ValidationAttribute
        {
            private int _Limit;
            public MinAge(int Limit) { // The constructor which we use in modal.
                this._Limit = Limit;
            }
            protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
            {
                    DateTime bday = DateTime.Parse(value.ToString());
                    DateTime today = DateTime.Today;
                    int age = today.Year - bday.Year;
                    if (bday > today.AddYears(-age))
                    {
                       age--; 
                    }
                    if (age < _Limit)
                    {
                        var result = new ValidationResult("Sorry you are not old enough");
                        return result; 
                    }
                   
                
                return null;
    
            }
        }
    

    SampleModal.cs

    [MinAge(18)] // 18 is the parameter of constructor. 
    public DateTime UserBirthDate { get; set; }
    

    IsValid runs after post and check the Limit. If age is not greater than the Limit (which we gave in modal!) than return ValidationResult