Monday, October 3, 2011

Date Validation JavaScript vs Code Behind vs RangeValidator

Although you can use a RangeValidator or CustomValidator to evaluate the contents of a textbox that captures a date, there might be instances in which you want to use a Client-Javascript to manually validate or manipulate what's typed.
Another possible situation is to do this on the code behind to validate the input at the moment the data is sent to the server.

After reading a few blogs and articles, below are two JavaScript functions that I've found extremely useful to validate dates .

-Validating the String
Notice how this function will evaluate a string input by using a regular expression. It separates the string and checks if the date elements fall within the numeric range established.

        function validateUSDate(strValue) {
 
            var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
 
            //check to see if in correct format
            if (!objRegExp.test(strValue))
                return false//doesn't match pattern, bad date
            else {
                var strSeparator = strValue.substring(2, 3)
                var arrayDate = strValue.split(strSeparator);
                //create a lookup for months not equal to Feb.
                var arrayLookup = { '01': 31, '03': 31,
                    '04': 30, '05': 31,
                    '06': 30, '07': 31,
                    '08': 31, '09': 30,
                    '10': 31, '11': 30, '12': 31
                }
                var intDay = parseInt(arrayDate[1], 10);
 
                //check if month value and day value agree
                if (arrayLookup[arrayDate[0]] != null) {
                    if (intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
                        return true//found in lookup table, good date
                }
 
                var intMonth = parseInt(arrayDate[0], 10);
                if (intMonth == 2) {
                    var intYear = parseInt(arrayDate[2]);
                    if (intDay > 0 && intDay < 29) {
                        return true;
                    }
                    else if (intDay == 29) {
                        if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
             (intYear % 400 == 0)) {
                            // year div by 4 and ((not div by 100) or div by 400) ->ok
                            return true;
                        }
                    }
                }
            }
            return false//any other values, bad date
        }


-Implementing validateUSDate
Below is another function that demonstrates how the validateUSDate function is being implemented in the JavaScript attached to the TextBox's OnBlur event. If the entered date fails. We default the date to Today.

        function fWorkDateValidate(str, object) {
            var dt = new Date();
            var dd = dt.getDate();
            var mm = dt.getMonth() + 1; //January is 0!
            var yyyy = dt.getFullYear();
 
            if (dd < 10) { dd = '0' + dd }
            if (mm < 10) { mm = '0' + mm } 
            
            var today = mm + '/' + dd + '/' + yyyy;
 
            if (validateUSDate(str) == false ) {
                alert('Invalid Work Date entered. Please specify date in format mm/dd/yyyy. Example: ' + today);
                object.value = today;
                object.focus();
            }
        }


-Textbox Date HTML

<asp:TextBox ID="TextBox3" runat="server"  style="font-familyArial, Helvetica, sans-serif;font-sizesmall;text-alignrightcolor#FF6600" Width="81px"onBlur="fWorkDateValidate(this.value, this);" MaxLength="10"></asp:TextBox>

I have to admit that I didn't write validateUSDate, I just modified it to fit my needs, I wanted to give credit to the authors but unfortunately since I tried code from several blogs, I can't find the exact pages where I took the function from. So credit is due to the author(s) whoever they are.

In case that you need to validate a date range in Code Behind. Below is an "if" statement to validate data elements using a Regular Expression. Notice how we can easily define the ranges, for example 0 to 1 and 0-9 for the month digits, then  a "/", then a 0-3 for the first digit of the day and so on... you get the idea.

if (String.IsNullOrEmpty(TextBox3.Text) ||
Regex.IsMatch(TextBox3.Text, @"^[0-1]?[0-9](/|-)[0-3]?[0-9](/|-)[1-2][0-9][0-9][0-9]$") == false)


-RangeValidator
Finally, let's review how can you use a RangeValidator to evaluate a date. It is a piece of cake. Just keep in mind that you need to specify a "type" of Date on your Validator and define the Minimum and Maximum Value.

<asp:RangeValidator ID="StDateValidator" runat="server" 
    ControlToValidate="TextBox1" Type="Date" 
    MinimumValue="01/21/1980" MaximumValue="12/31/2100" 
    ErrorMessage="Invalid Start Date. Please verify." 
    style="font-familyArial, Helvetica, sans-serif; 
    font-sizexx-smallfont-weight700"></asp:RangeValidator>

The validator will display the error message automatically, if the data on TextBox1 does not pass the validation.

Happy Coding,
Will




No comments:

Post a Comment