只允许输入数字型Textbox演示
有一个需求,需要在GridView中批量输入数字!
于是想到封装一个TextBox
代码如下:
public class NumberText : TextBox
{
private const string SMB_NUMBER_SCRIPT_ID = "{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
private const string SMB_NUMBER_SCRIPT_ONLY_HOOK = "return NumberEditor_KeyPress_Handle(this)";
private const string SMB_NUMBER_SCRIPT_ONLY_SCRIPT = "<script language=\"javascript\">\n" +
"function NumberEditor_KeyPress_Handle(ctrl)\n{{" +
"if(event.keyCode == 13) \n return true;\n" +
"if(event.keyCode<48 || event.keyCode>57 )\n" +
"return false;\n else \n return true;\n}}" +
"</script>";
private void RenderJavscript()
{
if (!Page.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), SMB_NUMBER_SCRIPT_ID, string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT, base.ID));
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("OnKeyPress", SMB_NUMBER_SCRIPT_ONLY_HOOK);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
RenderJavscript();
}
public NumberText()
: base()
{ }
}
{
private const string SMB_NUMBER_SCRIPT_ID = "{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
private const string SMB_NUMBER_SCRIPT_ONLY_HOOK = "return NumberEditor_KeyPress_Handle(this)";
private const string SMB_NUMBER_SCRIPT_ONLY_SCRIPT = "<script language=\"javascript\">\n" +
"function NumberEditor_KeyPress_Handle(ctrl)\n{{" +
"if(event.keyCode == 13) \n return true;\n" +
"if(event.keyCode<48 || event.keyCode>57 )\n" +
"return false;\n else \n return true;\n}}" +
"</script>";
private void RenderJavscript()
{
if (!Page.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), SMB_NUMBER_SCRIPT_ID, string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT, base.ID));
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("OnKeyPress", SMB_NUMBER_SCRIPT_ONLY_HOOK);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
RenderJavscript();
}
public NumberText()
: base()
{ }
}
关键点:第一,不要重复注册脚本,第二:要写在OnPreRender事件中
在引用的Page页面中,可以这样调用
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
NumberText number = new NumberText();
place1.Controls.Add(number);//放在一个PlaceHolder中
}
{
base.OnPreLoad(e);
NumberText number = new NumberText();
place1.Controls.Add(number);//放在一个PlaceHolder中
}
这样一来, 这个 NumberText只接收数字输入,如果需要小数点,可以再修改代码。不过,这里建议用两个NumberText来拼一个浮点数字,这样很好验证,因为小数字的位置不好固定。当然用正则也可以。
这里给出另外一个例子,首先,客户端验证:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsClientScriptBlockRegistered("ClientCheck"))
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ClientCheck", GetCheckScript());
}
if (txtAvePrice != null) { txtAvePrice.Attributes.Add("onblur", "ClientCheckFunction('" + txtAvePrice.ClientID + "',6,2)"); }
}
/// <summary>
/// 得到一段检测输入是否为有效数据的脚本
/// 使用方法: txtBox..Attributes.Add("onBlur", "ClientCheckFunction('txtBox',6,2)");
/// 说明检测的TextBox为 txtBox,并且整数位为6位,小数位为2位
/// </summary>
/// <returns></returns>
private string GetCheckScript()
{
return @"<script language=""javascript"">
function ClientCheckFunction(strid,nInt1,nInt2)
{
if(isNaN(document.getElementById((strid).value))
{
alert(""您输入的不是合法的数字。"");
document.getElementById((strid).focus();
document.getElementById((strid).select();
return false;
}
var sm = '^(\\d){1,'+nInt1+'}$|^(\\d){1,'+nInt1+'}\\.(\\d){1,'+nInt2+'}$';
var m = new RegExp(sm);
if(!m.test(document.getElementById((strid).value))
{
alert('输入的数字整数位最多'+nInt1+'位,小数位最多'+nInt2+'位');
document.getElementById((strid).focus();
document.getElementById((strid).select();
return false;
}
return true;
}</script>";
}
{
if (!Page.ClientScript.IsClientScriptBlockRegistered("ClientCheck"))
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ClientCheck", GetCheckScript());
}
if (txtAvePrice != null) { txtAvePrice.Attributes.Add("onblur", "ClientCheckFunction('" + txtAvePrice.ClientID + "',6,2)"); }
}
/// <summary>
/// 得到一段检测输入是否为有效数据的脚本
/// 使用方法: txtBox..Attributes.Add("onBlur", "ClientCheckFunction('txtBox',6,2)");
/// 说明检测的TextBox为 txtBox,并且整数位为6位,小数位为2位
/// </summary>
/// <returns></returns>
private string GetCheckScript()
{
return @"<script language=""javascript"">
function ClientCheckFunction(strid,nInt1,nInt2)
{
if(isNaN(document.getElementById((strid).value))
{
alert(""您输入的不是合法的数字。"");
document.getElementById((strid).focus();
document.getElementById((strid).select();
return false;
}
var sm = '^(\\d){1,'+nInt1+'}$|^(\\d){1,'+nInt1+'}\\.(\\d){1,'+nInt2+'}$';
var m = new RegExp(sm);
if(!m.test(document.getElementById((strid).value))
{
alert('输入的数字整数位最多'+nInt1+'位,小数位最多'+nInt2+'位');
document.getElementById((strid).focus();
document.getElementById((strid).select();
return false;
}
return true;
}</script>";
}
第二步,服务器端验证:以GridView为例
前台页面:
<asp:GridView ID="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">
<HeaderStyle BackColor="#1C5E55" ForeColor="White" HorizontalAlign="center" Height="30px" />
<AlternatingRowStyle BackColor="#f7f7f7" />
<RowStyle HorizontalAlign="center" Height="25px" BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<Columns>
<asp:TemplateField>
<HeaderStyle Width="60px" BackColor="#1C5E55" ForeColor="White" />
<HeaderTemplate>
分类编号</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="PKID" Text='<%# DataBinder.Eval(Container.DataItem,"CustomID")%>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderStyle Width="60px" BackColor="#1C5E55" ForeColor="White" />
<HeaderTemplate>
单位</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="C_Unit" Text="元/公斤" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最高价</HeaderTemplate>
<ItemTemplate>
最高价:
<asp:TextBox ID="txtMaxPrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最低价
</HeaderTemplate>
<ItemTemplate>
最低价:<asp:TextBox ID="txtMinPrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
平均价</HeaderTemplate>
<ItemTemplate>
平均价:
<asp:TextBox ID="txtAvePrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnInsert" Text="上传所填数据" runat="server" OnClientClick="javascript:return confirm('每天只能上传一次,重复上传会替换今日已上传的数据,确认要上传您的报价信息吗?')" />
BorderStyle="Solid" BorderColor="#ffffff" GridLines="Horizontal" CellSpacing="1"
Width="640" HorizontalAlign="center" BorderWidth="0px" EnableViewState="true"
DataKeyNames="CustomID">
<HeaderStyle BackColor="#1C5E55" ForeColor="White" HorizontalAlign="center" Height="30px" />
<AlternatingRowStyle BackColor="#f7f7f7" />
<RowStyle HorizontalAlign="center" Height="25px" BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<Columns>
<asp:TemplateField>
<HeaderStyle Width="60px" BackColor="#1C5E55" ForeColor="White" />
<HeaderTemplate>
分类编号</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="PKID" Text='<%# DataBinder.Eval(Container.DataItem,"CustomID")%>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderStyle Width="60px" BackColor="#1C5E55" ForeColor="White" />
<HeaderTemplate>
单位</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="C_Unit" Text="元/公斤" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最高价</HeaderTemplate>
<ItemTemplate>
最高价:
<asp:TextBox ID="txtMaxPrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最低价
</HeaderTemplate>
<ItemTemplate>
最低价:<asp:TextBox ID="txtMinPrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
平均价</HeaderTemplate>
<ItemTemplate>
平均价:
<asp:TextBox ID="txtAvePrice" runat="Server" CssClass="PriceStyle" MaxLength="6" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnInsert" Text="上传所填数据" runat="server" OnClientClick="javascript:return confirm('每天只能上传一次,重复上传会替换今日已上传的数据,确认要上传您的报价信息吗?')" />
后台代码:
private void btnInsert_Click(object sender, EventArgs e)
{
string str = CheckValid();
if (str.Trim().Length > 0) { this.Debug(str, this.ClientID); return; }
try { AddOneRecord(); }
catch (Exception ex)
{
Loghandle by Tony 2008.11.21
}
}
private string CheckValid()
{
string str = string.Empty;
if (null == GVList) { str = "上传数据为空!"; return str; }
string strPre1 = ErrorHandle.GetErrorInfoByID(155);//获取错误信息
string strPre2 = ErrorHandle.GetErrorInfoByID(156);//获取错误信息
TestProj.Price.Framework.Components.Price2 p = new TestProj.Price.Framework.Components.Price2();
Checkinput ////tony 2008.12.16
return str;
}
{
string str = CheckValid();
if (str.Trim().Length > 0) { this.Debug(str, this.ClientID); return; }
try { AddOneRecord(); }
catch (Exception ex)
{
Loghandle by Tony 2008.11.21
}
}
private string CheckValid()
{
string str = string.Empty;
if (null == GVList) { str = "上传数据为空!"; return str; }
string strPre1 = ErrorHandle.GetErrorInfoByID(155);//获取错误信息
string strPre2 = ErrorHandle.GetErrorInfoByID(156);//获取错误信息
TestProj.Price.Framework.Components.Price2 p = new TestProj.Price.Framework.Components.Price2();
Checkinput ////tony 2008.12.16
return str;
}
此时,每次验证结束时,将会提示用户一个编号,便于用户准确定位于错误行,以进行修改。