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

标签 javascript validation

我的页面上基本上有以下验证 - 这是一个单词规则,文本框中的描述不能超过 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/

相关文章:

javascript - 需要一种系统地处理NodeJS项目中的错误/异常/拒绝的方法

javascript - 如何不忘记在 Javascript 中到处使用 await?

bash - 提示用户确认

c# - 西里尔文文本验证

jquery - Bootstrap 中的开始日期和结束日期

jquery - 将信用卡验证添加到我的付款表单

javascript - $ 在 jQuery 中是什么意思?

javascript - 如何在 ES6 语法中导入 firebase-functions 和 firebase-admin 以便使用 Babel for Node 10 进行转译

javascript - 获取类内的 tagName 元素

php - Symfony3 自定义验证约束与参数抛出异常