只允许输入数字型Textbox演示

有一个需求,需要在GridView中批量输入数字!

于是想到封装一个TextBox

代码如下:

<!--{cps..0}-->publicclassNumberText:TextBox
ExpandedBlockStart.gifContractedBlock.gif
{
privateconststringSMB_NUMBER_SCRIPT_ID="{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
privateconststringSMB_NUMBER_SCRIPT_ONLY_HOOK="returnNumberEditor_KeyPress_Handle(this)";
privateconststringSMB_NUMBER_SCRIPT_ONLY_SCRIPT="<scriptlanguage=/"javascript/">/n"+
"functionNumberEditor_KeyPress_Handle(ctrl)/n{{"+
"if(event.keyCode==13)/nreturntrue;/n"+
"if(event.keyCode<48||event.keyCode>57)/n"+
"returnfalse;/nelse/nreturntrue;/n}}"+
"</script>";

privatevoidRenderJavscript()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
if(!Page.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),SMB_NUMBER_SCRIPT_ID,
string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT,base.ID));
}

}


protectedoverridevoidAddAttributesToRender(HtmlTextWriterwriter)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
base.AddAttributesToRender(writer);
writer.AddAttribute(
"OnKeyPress",SMB_NUMBER_SCRIPT_ONLY_HOOK);
}


protectedoverridevoidOnPreRender(EventArgse)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
base.OnPreRender(e);
RenderJavscript();
}


publicNumberText()
:
base()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{}
}

关键点:第一,不要重复注册脚本,第二:要写在OnPreRender事件中

在引用的Page页面中,可以这样调用 

<!--{cps..1}-->protectedoverridevoidOnPreLoad(EventArgse)
ExpandedBlockStart.gifContractedBlock.gif
{
base.OnPreLoad(e);
NumberTextnumber
=newNumberText();
place1.Controls.Add(number);
//放在一个PlaceHolder中
}

这样一来, 这个 NumberText只接收数字输入,如果需要小数点,可以再修改代码。不过,这里建议用两个NumberText来拼一个浮点数字,这样很好验证,因为小数字的位置不好固定。当然用正则也可以。

这里给出另外一个例子,首先,客户端验证:

<!--{cps..2}-->protectedvoidPage_Load(objectsender,EventArgse)
ExpandedBlockStart.gifContractedBlock.gif
{
if(!Page.ClientScript.IsClientScriptBlockRegistered("ClientCheck"))
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
"ClientCheck",GetCheckScript());
}

ExpandedSubBlockStart.gifContractedSubBlock.gif
if(txtAvePrice!=null){txtAvePrice.Attributes.Add("onblur","ClientCheckFunction('"+txtAvePrice.ClientID+"',6,2)");}
}

ExpandedBlockStart.gifContractedBlock.gif
/**////<summary>
///得到一段检测输入是否为有效数据的脚本
///使用方法:txtBox..Attributes.Add("onBlur","ClientCheckFunction('txtBox',6,2)");
///说明检测的TextBox为txtBox,并且整数位为6位,小数位为2位
///</summary>
///<returns></returns>

privatestringGetCheckScript()
ExpandedBlockStart.gifContractedBlock.gif
{
return@"<scriptlanguage=""javascript"">
functionClientCheckFunction(strid,nInt1,nInt2)
{
if(isNaN(document.getElementById((strid).value))
{
alert(""您输入的不是合法的数字。"");
document.getElementById((strid).focus();
document.getElementById((strid).select();
returnfalse;
}
varsm='^(//d){1,'+nInt1+'}$|^(//d){1,'+nInt1+'}//.(//d){1,'+nInt2+'}$';
varm=newRegExp(sm);
if(!m.test(document.getElementById((strid).value))
{
alert('输入的数字整数位最多'+nInt1+'位,小数位最多'+nInt2+'位');
document.getElementById((strid).focus();
document.getElementById((strid).select();
returnfalse;
}
returntrue;
}</script>
";
}

第二步,服务器端验证:以GridView为例

前台页面:

<!--{cps..3}--><asp:GridViewID="GVList"runat="server"ShowFooter="true"AutoGenerateColumns="False"
BorderStyle
="Solid"BorderColor="#ffffff"GridLines="Horizontal"CellSpacing="1"
Width
="640"HorizontalAlign="center"BorderWidth="0px"EnableViewState="true"
DataKeyNames
="CustomID">
<HeaderStyleBackColor="#1C5E55"ForeColor="White"HorizontalAlign="center"Height="30px"/>
<AlternatingRowStyleBackColor="#f7f7f7"/>
<RowStyleHorizontalAlign="center"Height="25px"BackColor="#E3EAEB"/>
<SelectedRowStyleBackColor="#C5BBAF"Font-Bold="True"ForeColor="#333333"/>
<Columns>
<asp:TemplateField>
<HeaderStyleWidth="60px"BackColor="#1C5E55"ForeColor="White"/>
<HeaderTemplate>
分类编号
</HeaderTemplate>
<ItemTemplate>
<asp:LabelID="PKID"Text='<%#DataBinder.Eval(Container.DataItem,"CustomID")%>'
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderStyleWidth="60px"BackColor="#1C5E55"ForeColor="White"/>
<HeaderTemplate>
单位
</HeaderTemplate>
<ItemTemplate>
<asp:LabelID="C_Unit"Text="元/公斤"runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最高价
</HeaderTemplate>
<ItemTemplate>
最高价:
<asp:TextBoxID="txtMaxPrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最低价
</HeaderTemplate>
<ItemTemplate>
最低价:
<asp:TextBoxID="txtMinPrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
平均价
</HeaderTemplate>
<ItemTemplate>
平均价:
<asp:TextBoxID="txtAvePrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ButtonID="btnInsert"Text="上传所填数据"runat="server"OnClientClick="javascript:returnconfirm('每天只能上传一次,重复上传会替换今日已上传的数据,确认要上传您的报价信息吗?')"/>


后台代码:

<!--{cps..8}-->None.gifprivatevoidbtnInsert_Click(objectsender,EventArgse)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif
stringstr=CheckValid();
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(str.Trim().Length>0)dot.gif{this.Debug(str,this.ClientID);return;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
trydot.gif{AddOneRecord();}
InBlock.gif
catch(Exceptionex)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif
LoghandlebyTony2008.11.21#regionLoghandlebyTony2008.11.21
InBlock.gif
//stringloginid=EmptyString;
InBlock.gif
//myLogger.Error(GetErrorMessage(loginid,1),ex);
InBlock.gif
//Debug(ErrorHandle.GetErrorInfoByID(999),this.ClientID);return;
ExpandedSubBlockEnd.gif
#endregion

ExpandedSubBlockEnd.gif}

ExpandedBlockEnd.gif}

None.gif
privatestringCheckValid()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif
stringstr=string.Empty;
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(null==GVList)dot.gif{str="上传数据为空!";returnstr;}
InBlock.gif
stringstrPre1=ErrorHandle.GetErrorInfoByID(155);//获取错误信息
InBlock.gif
stringstrPre2=ErrorHandle.GetErrorInfoByID(156);//获取错误信息
InBlock.gif
TestProj.Price.Framework.Components.Price2p=newTestProj.Price.Framework.Components.Price2();
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif
Checkinput////tony2008.12.16#regionCheckinput////tony2008.12.16
InBlock.gif
foreach(GridViewRowgvrinGVList.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifLabellb
=(Label)(gvr.FindControl("PKID"));
InBlock.gif
if(lb!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
inttemp=SQLParser.IntParse(lb.Text);
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(temp>0)dot.gif{p.P_Cate="---编号["+temp+"]";}
ExpandedSubBlockEnd.gif}

InBlock.gif
//验证平均价
InBlock.gif
TextBoxtb=(TextBox)(gvr.FindControl("txtAvePrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(tb==null||tb.Text==EmptyString)dot.gif{str=strPre1;returnstr+p.P_Cate;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
trydot.gif{p.P_AverPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}
ExpandedSubBlockStart.gifContractedSubBlock.gif
catchdot.gif{str=strPre2;returnstr+p.P_Cate;}
InBlock.gif
//验证最低价
InBlock.gif
tb=(TextBox)(gvr.FindControl("txtMinPrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(tb==null||tb.Text==EmptyString)dot.gif{str=strPre1;returnstr+p.P_Cate;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
trydot.gif{p.P_MinPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}
ExpandedSubBlockStart.gifContractedSubBlock.gif
catchdot.gif{str=strPre2;returnstr+p.P_Cate;}
InBlock.gif
//验证最高价
InBlock.gif
tb=(TextBox)(gvr.FindControl("txtMaxPrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(tb==null||tb.Text==EmptyString)dot.gif{str=strPre1;returnstr+p.P_Cate;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
trydot.gif{p.P_MaxPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}
ExpandedSubBlockStart.gifContractedSubBlock.gif
catchdot.gif{str=strPre2;returnstr+p.P_Cate;}
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(p.P_MinPrice>p.P_MaxPrice)dot.gif{str=ErrorHandle.GetErrorInfoByID(157);returnstr+p.P_Cate;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(p.P_AverPrice<p.P_MinPrice)dot.gif{str=ErrorHandle.GetErrorInfoByID(158);returnstr+p.P_Cate;}
ExpandedSubBlockStart.gifContractedSubBlock.gif
if(p.P_AverPrice>p.P_MaxPrice)dot.gif{str=ErrorHandle.GetErrorInfoByID(159);returnstr+p.P_Cate;}
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif
#endregion

InBlock.gif
returnstr;
ExpandedBlockEnd.gif}

此时,每次验证结束时,将会提示用户一个编号,便于用户准确定位于错误行,以进行修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值