2

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?

ElHashashin
  • 25
  • 1
  • 7

2 Answers2

8

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

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37
  • Thanks! I did what you say, but something is not working very well. For example, I create a Tourist 1 where is birthday was: 10-05-1990, and it work it very well. Then I try to create a Tourist 2 where is birthday is 12-22-1994, it should work well, but instead result on a “NullReferenceException was unhandled by user code”. Why? Note: The NullReferenceException pops up on “DateTime bday = DateTime.Parse(value.ToString());” – ElHashashin Jul 01 '16 at 19:40
  • @ElHashashin I guess the format is wrong. Did you check the format of first one? Is it 22th October or 12th December? – Berkay Yaylacı Jul 01 '16 at 19:44
  • @ElHashashin For the sucessful one the age variable should be 20. Does it? And what is null on that line? Value? – Berkay Yaylacı Jul 01 '16 at 19:50
  • I just want that the tourists must have +18 years old to do a reserve. I can't find the reason why Tourist 1 worked and Tourist 2 return a Exception... Both these tourists, in calculations, have more than 18 years – ElHashashin Jul 01 '16 at 19:54
  • What is null on that line is "Datetime" – ElHashashin Jul 01 '16 at 19:58
  • @ElHashashin I already got it. Trying to find solution for null reference exception. Is value null? – Berkay Yaylacı Jul 01 '16 at 19:58
  • Not possible, DateTime is type. Check the value parameter. @ElHashashin – Berkay Yaylacı Jul 01 '16 at 20:00
  • The value parameter(bday) is: {01/01/0001 00:00:00} – ElHashashin Jul 01 '16 at 20:05
  • @ElHashashin for tourist2 the date is not posting. 01/01/0001 is the default date. The solution is not wrong. – Berkay Yaylacı Jul 01 '16 at 20:06
  • Thanks! By the way, can you tell me what can I do for the tourist2 posting? – ElHashashin Jul 01 '16 at 20:10
  • @ElHashashin Update the question please. – Berkay Yaylacı Jul 01 '16 at 20:11
  • What is the best solution to resolve " for tourist2 the date is not posting"? – ElHashashin Jul 01 '16 at 20:16
  • @ElHashashin Uptade the main question with the changes. So everyone can see. – Berkay Yaylacı Jul 01 '16 at 20:18
  • This does not take into account the actual date (just the year) and will return incorrect results (for someone born in Dec 1998, it returns 18, despite the fact they they are only 17) –  Jul 01 '16 at 22:56
  • @StephenMuecke Good point but I explained just the Validation. They are the controls that he must do. – Berkay Yaylacı Jul 01 '16 at 23:01
  • 1
    You can see the correct code in [this answer](http://stackoverflow.com/questions/38038898/cant-apply-custom-validation-in-asp-net-mvc-model/38044396#38044396) :) –  Jul 01 '16 at 23:04
  • @StephenMuecke Thanks, I put the link on the answer. :) – Berkay Yaylacı Jul 01 '16 at 23:11
  • Actually, I assumed you would just adjust your code - i.e. `if (bday > today.AddYears(-age)){ age--; }` (my answer is a slightly different scenario because its based on comparing with a 2nd text box to enter a start date rather than comparing with today's date –  Jul 01 '16 at 23:16
2

Implement IValidatableObject on your tourist class.

Put your logic in the Validate() method.

You are using MVC so there is no MessageBox.Show(). The MVC model binder will automatically call you validation routine.

Here's another SO question with the details How do I use IValidatableObject?

Also your age logic is wrong. it needs to be

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
Community
  • 1
  • 1
Fran
  • 6,440
  • 1
  • 23
  • 35