简体   繁体   中英

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'. I have implemented the following server side validation in C# which is working fine

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. 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. 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 (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.

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). Or you can make such kind of validation manualy with ajax request.

This will keep your code from duplication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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