[英]How to allow only specific alphabets in a Textbox?
我可以使我的文本框僅允許L和P表示用戶輸入的前兩個字母嗎。例如:LP12345678901。 我希望這個例子能使問題具體化...
我嘗試了這個if(myTextBox.Text.StartsWith("LP"))
我也嘗試過正則表達式...但是我們不能用字母具體說明嗎?
試試這個代碼:
private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (myTextBox.Text.Length == 2)
{
if (myTextBox.Text.StartsWith("LP"))
{
//yourcode
}
else
{
myTextBox.Text = string.Empty;
}
}
}
這將為您提供幫助。
function Valid() {
var re = "^[LP][0-9]{11}$";
var str = document.getElementById("txtTSection").value;
var myArray = str.match(re);
if (myArray == null) {
alert("Incorrect Format");
$("#txtTSection").css("border-color", "red");
return false;
}
else {
$('#txtTSection').css('border-color', '');
}
}
<asp:TextBox ID="txtTSection" runat="server" CssClass="form-control" TabIndex="1" MaxLength="13" onfocusout="Valid()" ></asp:TextBox>
這不是技術解決方案,而是UX建議:
如果我總是必須輸入“ LP”作為首字母,並且不允許輸入其他字母或數字, 那么就不要每次都輸入它們 。 您已經確定“ LP” 是前兩個字母。 我再輸入一次是沒有意義的。 我不能從中得到任何好處。 即使輸入完美,我可以獲得的最佳結果是“無錯誤信息”。
如果您的前兩個字母必須為“ LP”,則在文本框前放置“ LP”作為標簽,並讓用戶僅輸入數字。 當您使用用戶輸入的內容時,請在其前面加上“ LP”。
public static bool ValidateSerNo(string ser)
{
if (!string.IsNullOrEmpty(ser))
{
if (ser.Trim().Length == 11)
{
if (ser.Trim().ToUpper().Substring(0, 2) == "LP")
{
if (Microsoft.VisualBasic.Information.IsNumeric(ser.Substring(2, 9)))
{
return true;
}
}
}
}
return false;
}
private void btn_Save_Click(object sender, EventArgs e)
{
if ((BattVoltMmnt.ValidateSerNo(txtbox_Serialno.Text.Trim().ToUpper()) == false))
{ MessageBox.Show("Enter correct serial number");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.