Like most programming tasks, client validation can be as simple or as more complex .In this article I am going to explain the Client Side Texbox Number/Characters Validation with JavaScript .
ASP.NET Client Side TextBox Validation
Like most programming tasks, client validation can be as simple or as more complex . Consider Employee Payroll Form , I am having Emp name, Salary, Address ,etc.
If any user trying to enter the characters into salary (Textbox) mean’s, It does'nt accepts the characters and it will show alert message and if trying to enter numbers into Emp Name Field also it will raise alert messages respectively.
The steps is as follow:
-
Open New Website,
-
Drag two Textboxes from toolbox (Web controls) and one asp.met Button control.
-
Wite the following code in html (Inlinecode).
<script language="javascript">
// Function to validate numbers
function clickButton(e)
{
if(navigator.appName.indexOf("Netscape")>(-1)){
if (e.keyCode == 13){
bt.click();
return false;
}
}
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){
if (event.keyCode < 48 || event.keyCode > 57){
//bt.click();
alert("Enter Numbers Only");
return false;
}
if(event.Length>3)
{
alert("Number Should be between 1 and 999")
}
}
}
// Function to validate characters/alphabets
function clickButton1(e1)
{
if(navigator.appName.indexOf("Netscape")>(-1)){
if (e1.keyCode == 13){
bt.click();
return false;
}
}
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){
if (event.keyCode < 97 || event.keyCode > 122){
//bt.click();
alert("Enter Characters Only");
return false;
}
}
}
</script>
Then in the CodeBehind File add the following procedure.
' attach the "number" javascript function to the textbox
Public Sub numbers(ByVal txtbox As System.Web.UI.WebControls.TextBox)
txtbox.Attributes.Add("onkeypress", "return clickButton(event)")
End Sub
' attach the "test" javascript function to the textbox
Public Sub test(ByVal txtbox1 As System.Web.UI.WebControls.TextBox)
txtbox1.Attributes.Add("onkeypress", "return clickButton1(event)")
End Sub
Then call this procedures (Numbers ,test) In the Page Load Event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' here "salary" is the id of the textbox, same applies to all procedures
numbers(salary)
numbers(mobileno)
numbers(homephone)
test(EmpName)
test(Address)
End Sub
In this way we are attaching our function to the onkeypress event of the textbox that will fire when user will press any key in these textboxes.
Surely this example will help in client side validation.
Happy coding.