Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Dynamic Date Validation using JavaScript

Posted by Viral Sarvaiya on July 11, 2009

The whole idea of the tutorial is to dynamically validate the data and display the results when the user is typing the same. The advantage of this approach is that it allows the user to correct its mistake first and the move to the next item

The article will cover the following aspects of data validation

1.     Enforcing date format dynamically i.e dd/mm/yyyy

2.     Validating date dynamically on key events.

3.     Validating whether the date entered is within the valid range

4.     Validating Birthdates

Validation and Date format Enforcement

The DateFormat function enforces the following conditions

1.     The characters entered should be numeric

2.     Automatically appends slashes as the user types it

It enforces numeric character check based on the keyboard key values thus simply do not allow the user to enter any character except number.

The next function ValidateDate as the name suggest simply validates the date. Using the JavaScript date functions and notifies the user whether the data is valid or not.

The compete script code for the two functions is given below

<script type = “text/javascript”>

var isShift=false;

var seperator = “/”;

function DateFormat(txt , keyCode)

{

if(keyCode==16)

isShift = true;

//Validate that its Numeric

if(((keyCode >= 48 && keyCode <= 57) || keyCode == 8 ||

keyCode <= 37 || keyCode <= 39 ||

(keyCode >= 96 && keyCode <= 105)) && isShift == false)

{

if ((txt.value.length == 2 || txt.value.length==5) && keyCode != 8  )

{

txt.value += seperator;

}

return true;

}

else

{

return false;

}

}

function ValidateDate(txt, keyCode)

{

if(keyCode==16)

isShift = false;

var val=txt.value;

var lblmesg = document.getElementById(“<%=lblMesg.ClientID%>”) ;

if(val.length == 10)

{

var splits = val.split(“/”);

var dt = new Date(splits[1] + “/” + splits[0] + “/” + splits[2]);

//Validation for Dates

if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1]

&& dt.getFullYear()==splits[2])

{

lblmesg.style.color=”green”;

lblmesg.innerHTML = “Valid Date”;

}

else

{

lblmesg.style.color=”red”;

lblmesg.innerHTML = “Invalid Date”;

return;

}

//Range Validation

if(txt.id.indexOf(“txtRange”) != -1)

RangeValidation(dt);

//BirthDate Validation

if(txt.id.indexOf(“txtBirthDate”) != -1)

BirthDateValidation(dt)

}

else if(val.length < 10)

{

lblmesg.style.color=”blue”;

lblmesg.innerHTML =

“Required dd/mm/yy format. Slashes will come up automatically.”;

}

}

</script>

You will notice that I am calling two more functions

1.     RangeValidation

2.     BirthDateValidation

RangeValidation

RangeValidation function validates that the date falls within a valid range for here I have used the range 01/01/1900 to 31/12/2099 If the date is not within the range it is termed as invalid.

Refer the script below

<script type = “text/javascript”>

function RangeValidation(dt)

{

var startrange = new Date(Date.parse(“01/01/1900”));

var endrange = new Date(Date.parse(“12/31/2099”));

var lblmesg = document.getElementById(“<%=lblMesg.ClientID%>”) ;

if (dt<startrange || dt>endrange)

{

lblmesg.style.color=”red”;

lblmesg.innerHTML = “Date should be between 01/01/1900 and 31/12/2099”;

}

}

</script>

BirthDateValidation

BirthDateValidation function validates the BirthDate based on two conditions

1.     The date should be less that equal to the current date

2.     The date should be greater that the difference between the current date and the date 100 years back.

<script type = “text/javascript”>

function BirthDateValidation(dt)

{

var dtToday = new Date();

var pastDate = new Date(Date.parse(dtToday.getMonth()+”/”+

dtToday.getDate()+”/”+parseInt(dtToday.getFullYear()-100)));

var lblmesg = document.getElementById(“<%=lblMesg.ClientID%>”);

if (dt<pastDate || dt>=dtToday)

{

lblmesg.style.color=”red”;

lblmesg.innerHTML = “Invalid BirthDate”;

}

else

{

lblmesg.style.color=”green”;

lblmesg.innerHTML = “Valid BirthDate”;

}

}

</script>

The script will be called on TextBox keyup and keydown events in the following way

<asp:TextBox ID=”txtValidate” runat=”server” MaxLength = “10”

onkeyup = “ValidateDate(this, event.keyCode)”

onkeydown = “return DateFormat(this, event.keyCode)”></asp:TextBox>

For more information Click Here

Advertisements

4 Responses to “Dynamic Date Validation using JavaScript”

  1. Thiagarajan said

    I am restricting thro data validation the input in multiple of x no. i would like to do and taht should be equal to or less than the other cell ref. How can i do this

  2. Thiagarajan said

    I am restricting thro data validation the input in multiple of x no. i would like to do and taht should be equal to or less than the other cell ref. How can i do this

    Reply

  3. viralsarvaiya said

    hi….
    For restrict the data from the input, the below javascript mau helpful to you…

    here i take the 2 text box named “txt1” and “txt2” and a button.

    in the click event of the button i call this javascript….

    function ValidMultiple() {
    if (document.getElementById(“txt1”).value != “”) {
    if (document.getElementById(“txt2”).value != “”) {
    var x = 5; //Your X for multiply
    var no1 = document.getElementById(“txt1”).value
    sum = no1 * x;
    if (sum > document.getElementById(“txt2”).value) {
    alert(“Your Message”);
    return false;
    }
    }
    else {
    alert(“Please Enter the Textbox2.”)
    return false;
    }
    }
    else {
    alert(“Please Enter the Textbox1.”)
    return false;
    }
    }

    may be this help full to you…
    enjoy coding…

  4. WP Themes said

    Good post and this fill someone in on helped me alot in my college assignement. Thanks you seeking your information.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: