简体   繁体   English

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

[英]Replicate C# Server Side Validation in Javascript

I basically have the following validation on my page - its a word rule in that a description in a text box cannot be greater than 3 words excluding the word 'and'. 我基本上在我的页面上进行了以下验证 - 它是一个单词规则,文本框中的描述不能超过3个单词,不包括单词'和'。 I have implemented the following server side validation in C# which is working fine 我在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");
    }
}

However I am having difficulty getting the same working in Javascript. 但是我很难在Javascript中使用相同的工作。 I have tried the following but it isnt working so far so hoping for someone that has a better knowledge of Javascript can see the error. 我已经尝试了以下但是它到目前为止还没有工作,所以希望有更好的Javascript知识的人可以看到错误。 Note the if is part of a bigger validate function that fires on the page - the alerts were just there to see if it got into this if (which it doesnt) - when this is block is removed the rest of the JS on the page is working fine. 注意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;
}

and the below is my regexWordRule defined at the very top of the js file. 以下是我在js文件最顶部定义的regexWordRule。

var regexWordRule = /[\S]+/;

You could find a better solution, but this approach came to my mind, so I am posting it: 你可以找到一个更好的解决方案,但我想到了这种方法,所以我发布了它:

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 . 在这里小提琴

In case you are using MVC3, you can use Remote validation on model (RemoteAttribute). 如果您使用的是MVC3,则可以在模型(RemoteAttribute)上使用远程验证。 Or you can make such kind of validation manualy with ajax request. 或者您可以使用ajax请求手动进行此类验证。

This will keep your code from duplication. 这将使您的代码不会重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM