How to validate an ASP.Net TextBox Control Using Javascript

Features :


1. Simple way to access JavaScript function and assign to a particular asp.net control
2. Using VB.Net as well as C#.Net Code for Embed the JavaScript Function to ASP.Net Control

CODE


put the below code inside the Head tag of .aspx file

'<'script language="javascript" type="text/javascript" '>'
//Because of restriction i put < > in between single quote(' ') please remove those (') from there.
function validateNumber(txtbox1)
{ var str=txtbox1.value;
var str1="0123456789";
var i=0;
for(i=0;i{
if(str1.indexOf(str.substring(i,i+1))<0 || str1.indexOf(str.substring(i,i+1))>str1.length)
{
txtbox1.value=str.substring(0,str.length-1);
alert("Enter Only Number");
txtbox1.focus();
break;
}
}
}
'<' '/'script '>'

//Add one textbox control of asp.net named as TextBox1



Then Add the following code into page load event

USING VB.Net



Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
TextBox1.Attributes.Add("onKeyup", "javascript:validateNumber(TextBox1)")
End Sub

USING C#.Net



protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("onKeyup", "javascript:validateNumber(TextBox1)");
}


Regards,
Manoranjan Sahoo
Visit My Blog : http://msahoo.wordpress.com


Article by Manoranjan Sahoo
If it helps you then Rate this. Best Regards, Manoranjan Sahoo http://www.dotnetsquare.com Blog: http://blog.msahoo.net

Follow Manoranjan Sahoo or read 63 articles authored by Manoranjan Sahoo

Comments

Author: Jayakumar.R06 Jun 2009 Member Level: Gold   Points : 1

hi
function TxtVal()
{
var t1=document.getElementById("TextBox1").value;
if (t1='Welcome')alert('Yes')else alert('False')
retrun false
}

TextBox1.Attributes.Add("onkeyup", "javascript:TxtVal());



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: