0

I am new to ASP.NET and I want to set the RangeValidator for verifying the date of birth who is above 18. I have set it, but it is not working.

How can I resolve it?

<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtDOB"
                    ErrorMessage="less than 18 " MaximumValue="01/01/1995" MinimumValue="01/01/1888"
                    SetFocusOnError="True" Type="Date" Style="color: #FF0000;"></asp:RangeValidator> 
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
BHARATH
  • 85
  • 1
  • 5
  • 11
  • visit http://stackoverflow.com/questions/939802/date-validation-with-asp-net-validator?rq=1 – Satpal Apr 02 '13 at 12:27

1 Answers1

3

I suggest you use an asp:CustomValidator with a clientside javascript function.

Custom Validator

You could do something like this (note, this is untested, just off the top of my head):

<asp:CustomValidator ID="CustomValidator1" runat="server" 
    EnableClientScript="true"
    ErrorMessage="less than 18"
    ClientValidationFunction="checkDate" 
    ControlToValidate="txtDOB">
</asp:CustomValidator> 

Assuming the date is written in this format "dd/MM/yyyy"

function checkDate() {
   var enteredDate=document.getElementById('<%=txtDOB.ClientID%>').value;
   var dateValues=enteredDate.split("/");
   var dateToCheck = new Date(dateValues[2], dateValues[1]-1, dateValues[0]);
   var today = new Date();
   var dateValid = new Date(today.getFullYear()-18, today.getMonth()-1, today.getDate());
   if (dateToCheck < dateValid) {
     args.IsValid = false;
   }
   else {
     args.IsValid = true;
   }
}

Note

  1. javascript uses 0 for January hence the -1 on the month.
  2. You should add a ServerValidation function to the custom validator in case javascript is disabled.
Jack Pettinger
  • 2,715
  • 1
  • 23
  • 37
  • Regarding point #2, can't he just check `Page.IsValid()` on the server-side? – Shai Cohen Apr 02 '13 at 12:41
  • 1
    @ShaiCohen He'll need custom code on server side too. – MikeSmithDev Apr 02 '13 at 12:48
  • @MikeSmithDev: Are you sure? It was my understanding that 'Page.Validate()' followed by `Page.IsValid` is the server-side validation of any and all validation server controls. From MSDN: **For this property to return true, all validation server controls in the current validation group must validate successfully. ** Am I missing something? – Shai Cohen Apr 02 '13 at 16:26
  • 1
    @ShaiCohen Yes... because you must specify `OnServerValidate` function for the custom validator.... where else do you think the validation code will come from? – MikeSmithDev Apr 02 '13 at 16:27
  • @MikeSmithDev: Thanks for teaching me something new. I appreciate it. – Shai Cohen Apr 02 '13 at 17:41