Hi amar,
Refer below sample.
HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var isShift = false;
var seperator = "/";
$(function () {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text") {
if (inputs[i].className.indexOf("validate") != 1) {
inputs[i].setAttribute("maxlength", 10);
inputs[i].onkeydown = function (e) {
return IsNumeric(this, e.keyCode);
};
inputs[i].onkeyup = function (e) {
ValidateDateFormat(this, e.keyCode);
};
}
}
}
});
function IsNumeric(input, keyCode) {
if (keyCode == 16) {
isShift = true;
}
if (((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode <= 37 || keyCode <= 39 || (keyCode >= 96 && keyCode <= 105)) && isShift == false) {
if ((input.value.length == 2 || input.value.length == 5) && keyCode != 8) {
input.value += seperator;
}
return true;
}
else {
return false;
}
};
function ValidateDateFormat(input, keyCode) {
var dateString = input.value;
if (keyCode == 16) {
isShift = false;
}
var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
if (regex.test(dateString) || dateString.length == 0) {
ShowHideError(input, "none");
} else {
ShowHideError(input, "block");
}
};
function ShowHideError(textbox, display) {
var row = textbox.parentNode.parentNode;
var errorMsg = row.getElementsByTagName("span")[0];
if (errorMsg != null) {
errorMsg.style.display = display;
}
};
</script>
<span class="error" style="display: none">Invalid Date. Only dd/MM/yyyy format allowed.</span>
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
TextBox text = new TextBox();
text.Attributes.Add("class", "validate");
form1.Controls.Add(text);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim text As TextBox = New TextBox()
text.Attributes.Add("class", "validate")
form1.Controls.Add(text)
End Sub
Screenshot