3

Does anyone know how can I validate the date format in client side in .net c#?

Example:

I have the following input, how can I validate the date formate to DD-MM-YYYY??

    <tr>
        <td align="right">Start Date:</td>
        <td><asp:TextBox runat="server" ID="activeDate" MaxLength="10" size="8"/>(DD-MM-YYYY)
        </td>
    </tr>
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

3 Answers3

4

Firstly, many people suggest using the Regex Validator in ASP.NET's toolkit to validate against the regex.

However this is not culture sensitive e.g. UK == DD/MM/YYYY whereas USA == MM/DD/YYYY and many people use ISO YYYY-MM-DD

A better way would be to use the CompareValidator and do a type check:

    <asp:CompareValidator ID="CompareValidator1" runat="server" 
           ControlToValidate="DateTextBox" ErrorMessage="Enter a valid date"
           Operator="DataTypeCheck" Type="Date" ValidationGroup="GroupName" />

You can couple this with a DateTimePicker, AJAX toolkit and a ScriptManager too for more functionality, though the above example will work.

    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
                     TagPrefix="ajaxToolkit" %>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:Label ID="lblDate" runat="server" Text="Date: "></asp:Label>
        <asp:TextBox ID="txtDate" runat="server" Width="140px"></asp:TextBox>
        <asp:Image ID="imgCalendar" runat="server" ImageUrl="~/Images/Calendar.png" />
        <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" 
               TargetControlID="txtDate" Format="MM/dd/yyyy" 
               PopupButtonID="imgCalendar" />
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
               ControlToValidate="txtDate" ErrorMessage="* Enter a valid date"
               Operator="DataTypeCheck" Type="Date" ValidationGroup="grpDate" />

http://blogs.mgtechgroup.com/markc/archive/2007/06/07/ASP.NET-Date-Validator.aspx

Darbio
  • 11,286
  • 12
  • 60
  • 100
  • Culture="ca-ES" will works for DD/MM/YYYY .. I think its better to use the culture . @JD is der any issue if I use the culture. – kbvishnu May 26 '11 at 10:35
  • Not at all, it's just something to be aware of if your users are going to be spread globally. A DatePicker will solve most of these issues with the graphical selection approach – Darbio May 26 '11 at 12:06
0

Are you open to using JQuery and the validation plugin?

An example doing pretty much what you're asking for is here.

Just inlining it for simplicity.

$.validator.addMethod(
"australianDate",
function(value, element) {
    // put your own logic here, this is just a (crappy) example
    return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"
);

And then on your form:

$('#myForm')
.validate({
    rules :
        myDate : {
            australianDate : true
        }
})
;
Community
  • 1
  • 1
Khepri
  • 9,547
  • 5
  • 45
  • 61
  • 1
    He specified client side and I find JQuery often has the simplest implementation. Opinions vary. – Khepri May 26 '11 at 05:27
  • The .NET class has client side validation, the javascript is automatically added using the CompareValidator. Sorry but I totally disagree, writing custom jQuery functions is not the simplest way to do this, and suggesting that it is shows a lack of base framework knowledge. – Darbio May 26 '11 at 05:31
  • I'm simply offering alternatives. You opinion is that adding a CompareValidator and a ScriptManager on the server side to generate the client side code we're looking for is easier than directly just adding client side code. Either will work. Options are a great thing. – Khepri May 26 '11 at 05:35
  • I am not saying your example doesn't work, I am saying that it is the wrong solution to this question. The danger is that you offer an alternative which does not validate the input on the server side, meaning that any wannabe hacker could turn off javascript, bypass any sort of validation, and cause all types of havoc. Dangerous road... – Darbio May 26 '11 at 05:39
  • I'll respectfully drop the argument at this point. The request was for an option for client side validation. That's been offered. – Khepri May 26 '11 at 05:45
  • @JD, "Why use jQuery when you can use the .NET types built into the BCL"? You might as well ask, "Why use ASP.NET/MVC?" Why would you eschew a standards-based solution (jQuery) over one that only works for people intimately familiar with the idiosyncrasies of WebForms? – Kirk Woll May 26 '11 at 06:14
  • @Kirk: As a fellow MVC/jQuery'r I agree, partially. However, the CompareValidator is definitely not only for people 'intimately familiar with WebForms'. The problem is that jQuery works on the client side, whichtoo many people forget and do not do server side validation on the input data - the first thing someone will try is to disable javascript to see if that is an easy way into your application. FWIW, in comments, the poster of this answer advocated that the 'simplest' way to validate input was to use jQuery - not taking into account any tools included with ASP.NET to make things easier – Darbio May 26 '11 at 06:23
  • I did take into account .NET based solutions. I came to the conclusion that I felt JQuery was the best option. That was my opinion after considering the options. Please stop belittling other people's opinions because you think they didn't consider the alternatives. – Khepri May 26 '11 at 06:30
  • 1
    @Khepri we can use the culture to set the date as per the required format.So we can if we are using some validation controls we can obtain it with out going for javascript.I think the validation will be done at client itself . – kbvishnu May 26 '11 at 10:39
0

use this javascript and call this onchange event of textbox

`

<script language = "Javascript">

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : dd/mm/yyyy")
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("Please enter a valid month")
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        alert("Please enter a valid day")
        return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date")
        return false
    }
return true
}

function ValidateForm(){
    var dt=document.frmSample.txtDate
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
    return true
 }

</script>`
Vikky
  • 752
  • 3
  • 15
  • 35
  • This is a very heavyweighted way of solving a solution which one .NET control can solve. – Darbio May 26 '11 at 05:44
  • if i can do it on client side without using a server control i think its better then to use a server control – Vikky May 26 '11 at 05:51
  • JD's arguments are rather anachronistic and parochial, so I wouldn't worry too much about the pitfalls of not using ASP.NET server-side controls -- those controls are a bit of a laughingstock and are one of the main reasons we have ASP.NET/MVC now. – Kirk Woll May 26 '11 at 06:12