Wednesday, 25 May 2011

Writing client side javascript to validate date.

Problem:
I was working with my project were I got stuck where I want to work with DATE data type at client side. When I click button I need to perform custom validation that validates the date entered by the user. I want to do this task using client side script.

Impact:
If you don’t use javascript then you have to use server side custom function. But then you are sending the request to server for validation.

Solution:
Use client side javascript function and make use of Date functionality available in it. Here the checkDate is the Function.
<script language="javascript"  type="text/javascript">
    function checkDate(sender, arguments) {
        //get the current date
        var tdate = new Date();
       
        //get year from current date
        var tyear = tdate.getFullYear();
        
        // Splits the date entered by userand gets in form of array
        // which contains date,month and year
       var cdate = arguments.Value.split('/');
               
        //check if age is greater than 18 and less than 90
        if ((tyear - cdate[2] > 18) && (tyear - cdate[2] < 90)) {

             //mark page as valid
             arguments.IsValid = true;
        }
        else {
            //mark page as invalid
            arguments.IsValid = false;
        }
    }
</script>

<asp:CustomValidator ID="CalendarCustomValidator"   runat="server" ControlToValidate="ShowDOB_label" 
ClientValidationFunction="checkDate"
Text="Age must be greater that 18 and less than 90">
</asp:CustomValidator>  

2 comments:

  1. Great!! This client side code is exactly what I was looking for. Now I can get this validation done without implementing code behind logic.

    ReplyDelete
  2. Betway India » 2021 Review and Bonus Code | Jtm Hub
    Betway India · Deposit: ₦5,000 bonus · Wagering: 김천 출장안마 ₦2,000 for live sports 평택 출장안마 · 충청북도 출장마사지 Deposit: ₦5,000 bonus · Odds: ₦1,000 on 포항 출장샵 live · Sports: Cricket, Premier League  Rating: 3.8 · ‎Review by 하남 출장샵 JT Hub

    ReplyDelete