1.新建aspx页面,往上面放几个TextBox服务端控件,还有一个服务端Button控件,取名btn_Submit
2.新建.js页面,将下面验证代码拷入js文件,取名check.js .
/* 检测指定文本框输入是否合法 */
function verifyInput(input)
{
var image;
var i;
var error = false;
/* 长度校验 */
if (strlen(input.value)>parseInt(input.maxsize))
{
alert(input.chname+"超出最大长度"+input.maxsize);
return false;
}
/* 非空校验 */
if (input.nullable=="no"&&isnull(input.value))
{
alert(input.chname+"不能为空");
return false;
}
/* 数据类型校验 */
if (input.nullable=="no" || !isnull(input.value))
{
switch(input.datatype)
{
case "number": if (isnumber(input.value)==false)
{
alert(input.chname+"值应该全为数字");
return false;
}
break;
case "text": if (IsSafeQuerystring(input.value)==false)
{
alert(input.chname+"值包含非法字符");
return false;
}
break;
case "email": if (/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(input.value)==false)
{
alert(input.chname+"值应该为合法的邮件地址");
return false;
}
break;
case "mobile": if (/^[0|1]{1,2}[3|5]\d{9}$/.test(input.value)==false)
{
alert(input.chname+"不是合法的手机号码");
return false;
}
break;
case "telephone": if (/^(\d{7,13}|\d{7,13}-\d{3,4})$/.test(input.value)==false)
{
alert(input.chname+"不是合法的电话号码");
return false;
}
break;
case "dropdown":
if (/请选择*/.test(input.options[input.options.selectedIndex].text)==true)
{
alert(input.chname+"必须选择一个值");
return false;
}
break;
case "radio":
if (input.options.selectedIndex==-1)
{
alert(input.chname+"必须选择一个值");
return false;
}
break;
case "hour":
if (isnumber(input.value)==false)
{
alert(input.chname+"应该输入数字");
return false;
}
if( parseInt(input.value,10)>23 || parseInt(input.value,10)<0)
{
alert(input.chname+"的数值应该在00和23之间");
return false;
}
if( strlen(input.value)!=2)
{
alert(input.chname+"应输入两位数字");
return false;
}
break;
case "minute":
if (isnumber(input.value)==false)
{
alert(input.chname+"应该输入数字");
return false;
}
if( parseInt(input.value,10)>59 ||parseInt(input.value,10)<0)
{
alert(input.chname+"的数值应该在00和59之间");
return false;
}
if( strlen(input.value)!=2)
{
alert(input.chname+"应输入两位数字");
return false;
}
break;
/* 在这里可以添加多个自定义数据类型的校验判断 */
/* case datatype1: ... ; break; */
/* case datatype2: ... ; break; */
/* ....................................*/
default : break;
}
}
return true;
}
3.在.aspx的html页面上添加引用
<script language="javascript"><!--#INCLUDE VIRTUAL="check.js" --></script>
4.在.aspx.cs文件Page_Load里添加代码
if(!Ispostback)
{
this.TextBox1.Attributes.Add("chname", "角色名称"); //要提示的信息
this.TextBox1.Attributes.Add("maxsize", "20"); //最大长度
this.TextBox1.Attributes.Add("nullable", "yes"); //是否为空
this.TextBox1.Attributes.Add("datatype", "text"); //什么类型的,js里面有好多类型如:number等
this.TextBox2.Attributes.Add("chname", "角色名称");
this.TextBox2.Attributes.Add("maxsize", "30");
this.TextBox2.Attributes.Add("nullable", "no");
this.TextBox2.Attributes.Add("datatype", "number");
//为按钮添加onclick事件,
this.btn_Submit.Attributes["onclick"] = "javascript:return verifyAll(window.form1);";
}
5.单击btn_Submit时会先激发客户端事件,如果不符合要求会弹出错误的提示信息.点击确定,会自动定位到出错的TextBox上.