类似与阿里巴巴的js表单验证 同时实现前后台验证 [分享]
本文转自:http://www.solo168.com/post/70.html
类似与阿里巴巴的表单验证 不用控件自己写代码 代码分为前台JS验证和后台程序验证
分这两部分验证主要是为了避免有些用户通过设置浏览器的安全级别绕过前台JS验证,
所以后台专门写了另一层验证。
<!--前台页面JS验证-->
<script src="/js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
<!--统一得到文本框值方法-->
function GetInputID(id)
{
return (document.getElementById) ? document.getElementById(id) : document.all[id] ;
}
<!--验证表单不能为空-->
function CheckEmpty(inputName,spanName)
{
var strVal=GetInputID(inputName).value;
if(strVal.length==0)
{
GetInputID(spanName).innerHTML="对号";
return true;
}
else
{
GetInputID(spanName).innerHTML="请输入联系人";
return false;
}
}
</script>
<script type="text/javascript">
<!--表单调用JS验证-->
$(document).ready(function()
{
$("#txtContacter").blur(function()
{
CheckEmpty('txtContacter','span_contact');
});
});
<!--按钮调用整体JS再一次验证-->
function AllInputCheck()
{
var strContact=true;
if(!CheckEmpty('txtContacter','span_contact'))
{
strContact=false;
}
return strContact;
}
</script>
<!--页面上的控件-->
<asp:TextBox ID="txtContacter" CssClass="text" runat="server" MaxLength="20" Width="80"></asp:TextBox><span id="span_contact"></span>
<asp:Button ID="btnSure" runat="server" Text="确认提交" OnClientClick="return AllInputCheck()" OnClick="btnSure_Click" />
<!--后台代码 验证-->
#region 后台验证
bool strFlag = true;
string strError = "<ul class='nojs'>";
if (txtContacter.Text== "")
{
strError += "<li>·请输入联系人</li>";
strFlag = false;
}
#endregion 后台验证
#region 判读验证后 注册
if (strFlag)
{
//验证通过 做你想做的事
}
else
{
//验证失败
strError += "</ul>";
liError.Text = strError; //liError为前台显示验证错误的控件
}
#endregion 判读验证后 注册
通过这两层验证你就可以实现类似阿里巴巴那样炫目的表单验证了...
本文转自:http://www.solo168.com/post/70.html