如何只允许文本框中的特定字母?

时间:2015-06-30 05:29:31

标签: c# textbox

我可以让我的文本框只允许L& P表示用户输入的两个字母。例如:LP12345678901。我希望这个例子能够使问题具体化......

我试过这个 if(myTextBox.Text.StartsWith("LP"))

我也尝试了正则表达式...但我们不能在字母表中具体说明吗?

4 个答案:

答案 0 :(得分:1)

试试这段代码:

    private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
         if (myTextBox.Text.Length == 2)
          { 
                 if (myTextBox.Text.StartsWith("LP"))
                 {
                    //yourcode
                 }
                 else
                 {
                         myTextBox.Text = string.Empty;
                 }
           }
}

答案 1 :(得分:1)

这会对你有帮助。

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>

答案 2 :(得分:0)

这不是技术解决方案,而是UX建议:

如果我总是要输入&#34; LP&#34;作为第一个字母,我不允许输入不同的字母或数字,然后不要让我每次输入。你已经决定&#34; LP&#34; 前两个字母。我再没有打字就没有意义了。我无法从中获得任何好处。即使我完美地输入它,我能达到的最好结果是&#34;没有错误信息&#34;。

如果你的前两个字母必须是&#34; LP&#34;然后把&#34; LP&#34;作为文本框之前的标签,并使用户只输入数字。当您使用用户输入的内容时,请使用&#34; LP&#34;作为前缀。

答案 3 :(得分:0)

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"); 

        }
     }
相关问题