我的页面上基本上有以下验证 - 这是一个单词规则,文本框中的描述不能超过 3 个单词,不包括单词“and”。我已经在 C# 中实现了以下服务器端验证,它工作正常
if (Desc.Trim().ToString() != "")
{
MatchCollection collection = Regex.Matches(Desc.Replace("and", ""), @"[\S]+");
if (collection.Count > 3)
{
ErrorMsg.Append("Description should contain at most 3 words(excluding 'and').");
ErrorMsg.Append("\\n");
}
}
但是我很难在 Javascript 中实现同样的效果。我已经尝试了以下方法,但到目前为止还没有用,所以希望对 Javascript 有更好了解的人可以看到错误。请注意 if 是在页面上触发的更大验证函数的一部分 - 警报只是在那里查看它是否进入这个 if (它没有) - 当这个 block 被删除时页面上的其余 JS 是工作正常。
if (Desc.val().trim() != "")
{
alert('1');
!regexWordRule.test(Desc.val());
alert('2');
if (Desc.val().match(regexWordRule).length > 3)
{
errorText += "Description should contain at most 3 words(excluding 'and').";
}
valid = false;
}
下面是我在 js 文件最顶部定义的 regexWordRule。
var regexWordRule = /[\S]+/;
最佳答案
您可以找到更好的解决方案,但我想到了这种方法,所以我将其发布:
var input = "and lorem and ipsum";
// remove ands
var deandizedinput = input.replace(/\band\b/g, ' ');
// replace all white spaces with a single space
var normalizedinput = deandizedinput.replace(/\s+/g, ' ');
// split the input and count words
var wordcount = normalizedinput.trim().split(' ').length;
fiddle here .
关于javascript - 在 Javascript 中复制 C# 服务器端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12350769/