检查字符串中的无效字符
check string for invalid characters
我在表单中有一个名为 Comment
的文本框。在用户输入他们的评论并单击保存按钮后,我想通过这个评论字符串搜索任何无效字符,如句号、逗号、括号等。
如果字符串包含这些字符中的任何一个,那么我想抛出一个异常。
我知道在 javascript 中您可以使用 RegularExpressionValidator
并使用 ValidationExpression="^[a-zA-Z0-9]*$"
检查验证,但是您如何在后面的代码中执行此操作?
现在我只是检查评论是否为空,但如何检查评论是否包含数字和字母以外的任何内容?
if (string.IsNullOrEmpty(txtComment.Text))
{
throw new Exception("You must enter a comment");
}
使用Regex
也是一样的逻辑
Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
Match match = regex.Match(txtComment.Text);
if (!match.Success)
{
throw new Exception("You must enter a valid comment");
}
// Basic Regex pattern that only allows numbers,
// lower & upper alpha, underscore and space
static public string pattern = "[^0-9a-zA-Z_ ]";
static public string Sanitize(string input, string pattern, string replace)
{
if (input == null)
{
return null;
}
else
{
//Create a regular expression object
Regex rx;
rx = new Regex(pattern);
// Use the replace function of Regex to sanitize the input string.
// Replace our matches with the replacement string, as the matching
// characters will be the ones we don't want in the input string.
return rx.Replace(input, replace);
}
}
我在表单中有一个名为 Comment
的文本框。在用户输入他们的评论并单击保存按钮后,我想通过这个评论字符串搜索任何无效字符,如句号、逗号、括号等。
如果字符串包含这些字符中的任何一个,那么我想抛出一个异常。
我知道在 javascript 中您可以使用 RegularExpressionValidator
并使用 ValidationExpression="^[a-zA-Z0-9]*$"
检查验证,但是您如何在后面的代码中执行此操作?
现在我只是检查评论是否为空,但如何检查评论是否包含数字和字母以外的任何内容?
if (string.IsNullOrEmpty(txtComment.Text))
{
throw new Exception("You must enter a comment");
}
使用Regex
Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
Match match = regex.Match(txtComment.Text);
if (!match.Success)
{
throw new Exception("You must enter a valid comment");
}
// Basic Regex pattern that only allows numbers,
// lower & upper alpha, underscore and space
static public string pattern = "[^0-9a-zA-Z_ ]";
static public string Sanitize(string input, string pattern, string replace)
{
if (input == null)
{
return null;
}
else
{
//Create a regular expression object
Regex rx;
rx = new Regex(pattern);
// Use the replace function of Regex to sanitize the input string.
// Replace our matches with the replacement string, as the matching
// characters will be the ones we don't want in the input string.
return rx.Replace(input, replace);
}
}