在Javascript中复制C#服务器端验证

Replicate C# Server Side Validation in Javascript

本文关键字:服务器端 验证 复制 Javascript      更新时间:2023-09-26

我的页面上基本上有以下验证-这是一个单词规则,因为文本框中的描述不能超过3个单词,不包括单词"answers"。我已经在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(它没有进入)-当这个块被删除时,页面上的其余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;

在这里打闹。

如果您使用的是MVC3,则可以对模型(RemoteAttribute)使用远程验证。或者,您可以使用ajax请求手动进行此类验证。

这样可以防止代码重复。