[英]How to allow only digits and one decimal point in a web form textbox
我是編程新手,所以我希望你保持開放的心態。 我在 Visual Studio 2013 中使用 web forms。我使用的語言是 C#。 我有一個文本框,我只想接受數字和一個小數點。 我怎樣才能做到這一點。
note: I've seen lots of code but most of them are using the KeyPress event which I assume is not valid for web forms because when I go to the events section in the property window of my textbox I only see one event which is TextChanged .
任何提示都會幫助我真的需要這個。
提前致謝。
您可以為此目的使用JavaScript 。 使用javascript將限制用戶輸入除數字和小數點以外的所有字符。 在aspx頁面的頂部添加以下Javascript。
<SCRIPT language=Javascript>
function isDecimal(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var parts = evt.srcElement.value.split('.');
if(parts.length > 1 && charCode==46)
return false;
else
{
if (charCode == 46 || (charCode >= 48 && charCode <= 57))
return true;
return false;
}
}
</SCRIPT>
並在文本框控件中包含以下代碼段
onkeypress =“返回isDecimal(事件)”
您可以使用以下表達式編寫正則表達式驗證器: ^\\d+(\\.\\d+)?$
這樣可以確保您擁有數字,例如100
或11220.22
。 正則表達式的解釋在這里 。
編輯:根據您的評論,問題在於\\
在C#中也是一個特殊字符,因此需要在類后面的代碼中進行轉義,因此在您的情況下,表達式將如下所示: ^\\\\d+(\\\\.\\\\d+)?$
。
我認為,一個更好的方法,不過,會使用一個正則表達式驗證如圖所示這里 。 這應該只驗證一次文本(按提交時)。 構建它的方式(在后面的代碼中)可能有點繁瑣,因為每次更改文本時,它很可能會觸發服務器端事件。 另外,如果使用ASP.NET驗證程序,我認為(如果有內存的話)不需要轉義正則表達式。
編輯2:此正則表達式應幫助: ^[1-9]\\\\d*(\\\\.\\\\d+)?$
看看這個線程,它描述了幾種方法: http : //bytes.com/topic/net/answers/562094-restrict-user-enter-numeric-value-textbox
我相信就像已經提到過npinti一樣,驗證器將是一種方法。 您可能需要使用一種JavaScript方法,鏈接文章(底部)中顯示了一種方法。
您可以將驗證器的目標設置為文本框,並將正則表達式\\ d +(。\\ d)用於?
有關更多信息,請在此處檢查 簡單正則表達式,精度為2的十進制
另一個例子 ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
你可以試試這個:onkeypress 屬性
<asp:TextBox ID="Budget" runat="server" class="form-control" onkeypress="if(event.keyCode != 46 && event.keyCode > 31 && (event.keyCode < 48 || event.keyCode > 57))event.returnValue=false;" placeholder="Budget"></asp:TextBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.