验证文本框 [英] validation on atext box
问题描述
嗨!
我创建了一个具有两个文本框的表单
在文本框1中用于用户ID
小写字母仅允许使用-"和字母"
我如何验证文本box1
hi!
i create a form which has two text box
in text box1 is for user id
where only "-" and "alphabets" are allowed in lower case
how i have to validate the text box1
推荐答案
处理TextBox.KeyPress事件:
Handle the TextBox.KeyPress event:
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!((e.KeyChar >= ''a'' && e.KeyChar <= ''z'') || e.KeyChar == ''-''))
{
e.Handled = true;
}
}
我启用此功能,请告诉我我必须对-"使用什么,因为分隔符不起作用"
"i make this function can u please tell me what i have to use for "-" becouse seperator is not working"
private string RemoveNonAlphabets(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
if(char.IsLetter(str[i]) || char.IsSeparator(str[i]))
sb.Append(str[i]);
} return sb.ToString();
}
要满足您最初的问题目标,请使用IsLower而不是IsLetter-后者允许使用"A" ..''Z"以及"a" .. z"
不要使用IsSeparator-它会检查:
To meet your original question objectives, use IsLower rather than IsLetter - the latter allows ''A''..''Z'' as well as ''a''..''z''
Don''t use IsSeparator - it checks for:
The Unicode standard recognizes three subcategories of separators:
Space separators (the UnicodeCategory.SpaceSeparator category), which includes characters such as \u0020.
Line separators (the UnicodeCategory.LineSeparator category), which includes \u2028.
Paragraph separators (the UnicodeCategory.ParagraphSeparator category), which includes \u2029.
(来自MSDN: http://msdn.microsoft.com/en-us/library/cta536cf.aspx [ ^ ])
在上面的示例中使用-".
(Taken from MSDN: http://msdn.microsoft.com/en-us/library/cta536cf.aspx[^])
Use ''-'' as in my example above.
我假设您的意思是一个ASP.NET页面,如果是这种情况,请在下面尝试,
I assume you mean a ASP.NET page, if that is the situation then please try below,
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="reValidatorTextBox" ControlToValidate="txtTest"
ValidationExpression="^[a-zA-Z-]+
" runat = " ErrorMessage = " 仅字母和-" ">< / asp:RegularExpressionValidator > < asp:按钮ID = " runat = " Text = " />
" runat="server" ErrorMessage="Only alphabets and -"></asp:RegularExpressionValidator> <asp:Button ID="btnTest" runat="server" Text="Button" />
希望对您有所帮助:)
Hope it might help you :)
这篇关于验证文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!