1

I want to be able to validate that a birthdate entered is 18 or older. I have searched and found numerous posts about this. However, I don't understand

1) Why MS didn't build this into MVC3 like the other validations such as string, email, password, etc. 2) why when I get the javascript in place to make the dates correctly validate, the other unobtrustive js doesn't work any more.

I want to have client side validation before submit yet, dates doesn't seem to work well with this. All the rest does.

Am I missing something ?

some code I've tried in my model

   #1)    [Display(Name = "Date of Birth (must be at least 18) ")]
    public DateTime Birthdate
    {
        get
        {
            if ((SelectedBMonth != "0") && (SelectedBday != "0") && (SelectedBYear != "0"))
                return DateTime.Parse(SelectedBMonth + "/" + SelectedBday + "/" + SelectedBYear);
            else 
                return DateTime.MinValue;
        }
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Birthdate.Date > DateTime.Today.AddYears(-18)) 
            yield return new ValidationResult("You must be at least 18 years old to register", new[] { "Birthdate" });
    }
#2)
         [Required]        
    [CustomValidation(typeof(RegisterModel), "ValidateDOBDate")] 
    [DataType(DataType.Date)]
    [Display(Name = "Date of Birth")]        
    public DateTime DateOfBirth { get; set; }

    public static ValidationResult ValidateDOBDate(DateTime DateOfBirthtovalidate) { if (DateOfBirthtovalidate.Date > DateTime.Now.AddYears(-18)) { return new ValidationResult("User should be atleast 18 years old."); } if (DateOfBirthtovalidate.Date < DateTime.Now.AddYears(-150)) { return new ValidationResult("Please put a valid date"); } return ValidationResult.Success; } 

#3)
       public class DateofBirthAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value == null || (DateTime)value < DateTime.Today.AddYears(-18))
                return false;

            return true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "dateofbirth"
            };
        }
    }

    [Required]
    [Display(Name = "Date of Birth")]
    [DateofBirth(ErrorMessage = "User must be at least 18")]
    public DateTime Birthdate { get; set; }

View : 

 <div class="editor-label">
            @Html.LabelFor(m => m.Birthdate)
        </div>
        <div class="editor-field">                
        @Html.TextBoxFor(x => x.Birthdate)
@Html.ValidationMessageFor(x => x.Birthdate)
</div>

Top of view before beginform:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">    </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MyScripts.js")" type="text/javascript"></script>
<script type="text/javascript">
// we add a custom jquery validation method
jQuery.validator.addMethod('greaterThan', function (value, element, params) {
    if (!/Invalid|NaN/.test(new Date(value))) {
        return new Date(value) > new Date($(params).val());
    }
    return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val()));
}, '');

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('dateofbirth', {}, function (options) {
    options.rules['greaterThan'] = true;
    options.messages['greaterThan'] = options.message;
});
</script>
DavieDave
  • 1,394
  • 2
  • 18
  • 35
  • Could you please provide an example of the code you are trying, and also link to any resources that you have already tried? – beyond-code Dec 03 '12 at 17:07
  • Maybe this is something similar, I don´t know? [StackOverflow example](http://stackoverflow.com/questions/6250821/date-validation-using-asp-net-mvc-3-0) – gardarvalur Dec 03 '12 at 17:26
  • You don't need any parameter, you can just compare the birthdate with current date. – Jahan Zinedine Dec 03 '12 at 17:53

1 Answers1

0

That's a dynamic validation which is dependant on current date, and it's not available in default validation options.

You can easily implement it but there is no client side validation generated.

You must implement the client side javascript validation also.

Fore more information about adding a new Validation to ASP.NET MVC check out this ASP .Net MVC 3 unobtrusive custom client validation.

Community
  • 1
  • 1
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
  • I tried this too as #3 above... but it didn't seem to do anything. – DavieDave Dec 03 '12 at 18:00
  • On client side or server side? – Jahan Zinedine Dec 03 '12 at 18:02
  • on client side, I had the server side working at one point in this situation. – DavieDave Dec 03 '12 at 18:12
  • will have to recreate it.. I abandoned it a day or two ago. I have some js code that validates my date now, but the unobtrusive js that is in place for the model now does not show the errors its supposed to. – DavieDave Dec 03 '12 at 18:18
  • As I see there is no parameter sent to greaterThan method in javascript, debug your javascript code using Firebug or Developer Tools of Chrome or IE or Safari, set a breakpoint on both methods in and check the contents of your variables. If no chance then instead of defining two methods, just define a method specifically for your BirthDate, it will simplify the problem – Jahan Zinedine Dec 03 '12 at 19:04
  • this all works now. one thing that would make this better however is if I could make this work with drop downs for the day month year. Is there a quick way to tell me how to do that piece? – DavieDave Dec 04 '12 at 00:31
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/20600/discussion-between-daviedave-and-jani) – DavieDave Dec 05 '12 at 04:33