从客户端正则表达式实现服务器端正则表达式验证
问题描述:
我有一个文本框,我只想要字母数字字符和一些标点符号;该jsFiddle是在这里,JavaScript实现看起来是这样的:从客户端正则表达式实现服务器端正则表达式验证
var TheCleanString = TheInput.replace(/(^\s+|[^a-zA-Z0-9 \\s\(\)\.\-]+)/g, '');
正如你所看到的,这个只允许字母数字字符,删除前导空格,并允许括号,点和连字符。
现在我想使用SAME正则表达式来验证来自客户端的字符串是否传递了此正则表达式。我有这样的事情:
public bool MadeIt(TheCandidateString)
{
if (TheCandidateString passed this
regex /(^\s+|[^a-zA-Z0-9 \\s\(\)\.\-]+)/g
then return true)
}
这样做的最好方法是什么?
谢谢。
答
public bool MadeIt(string TheCandidateString)
{
string regex= @"yourRegex";
var match = Regex.Match(TheCandidateString, regex, RegexOptions.IgnoreCase);
return match.Success;
}
如果您使用的是asp.net,请查看RegEx验证程序 - 它会在两边检查它 – Liath