Reputation: 4319
I have a textbox for entering date.Textbox should allow only dd/MM/yyyy format.How can i check it using javascript
Upvotes: 0
Views: 943
Reputation: 272416
You're using dd/mm/yyyy to validate dates -- you can use the JavaScript date object to validate dates but its trickier in this case:
var o = document.form1.date1; // o is a reference to the textbox
var r = /^(\d+)\/(\d+)\/(\d+)$/.exec( o.value ); // extract day, month and year
if ( ! r )
{
// invalid date -- pattern matching failed
}
var d = parseInt( r[ 1 ], 10 );
var m = parseInt( r[ 2 ], 10 );
var y = parseInt( r[ 3 ], 10 );
var c = new Date( y, m - 1, d ); // month is zero based but year and day are not
if ( isNaN( c ) )
{
// invalid date -- javascript could not make a date out of the three numbers
}
Upvotes: 1
Reputation: 85685
If you're using WebForms, just use a CompareValidator:
<asp:CompareValidator runat="server" ControlToValidate="txtInput" Type="Date"
Operator="DataTypeCheck" ErrorMessage="That's not a valid date!" />
Upvotes: 2