简体   繁体   English

asp.net C#中的文本框验证仅将前两个字符作为“字符”

[英]TextBox validation in asp.net C# for first 2 characters as “Character” only

I need a validation in text box that when i enter some value in text box, the first two characters should be characters only, followed by 5 int's, then a hyphen and then two int's. 我需要在文本框中进行验证,当我在文本框中输入一些值时,前两个字符应仅是字符,然后是5个整数,然后是一个连字符,再两个是整数。 Eg : EM12345-23. 例如:EM12345-23。 Can i achieve such validation at aspx level only.? 我只能在aspx级别上实现这种验证吗?

User asp RegularExpressionValidator 用户asp RegularExpressionValidator

Here is an example: 这是一个例子:

<asp:RegularExpressionValidator Display="Dynamic" ID="regexp" runat="server" ControlToValidate="regexptest" ValidationGroup="regexptest" ValidationExpression="^[A-Za-z]{2}.+$">

Yes. 是。 You can. 您可以。 Use a Regex Validator . 使用正则表达式验证器

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
     ControlToValidate="txtCode" Display="Dynamic" ErrorMessage="Invalid Code"
     ForeColor="Red" ValidationExpression="^[A-Za-z]{2}\d{5}-\d{2}$">  
</asp:RegularExpressionValidator>

Yes. 是。 Use a Regex expression. 使用正则表达式。 That can be written as 可以写成

string regex = ^[A-Z]{2}\d{5}-\d{2}$

This will cause the first 2 characters only to be capital letters. 这将导致前2个字符仅是大写字母。 If you want them to be anything them use 如果您希望他们成为他们使用的任何东西

string regex = ^[A-Za-z]{2}\d{5}-\d{2}$

Validate your input. 验证您的输入。

Regex regex = new Regex(regex);
bool result = regex.IsMatch(textBox1.Text);

if(result)
{
    //success
}
else
{
    //Failed
}

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM