C # server side validation replication in Javascript

I basically have the following check on my page - this is a word rule in which the description in the text box cannot be more than three words, excluding the word "and". I performed the following server side check in C #, which works 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, it is difficult for me to get the same in Javascript. I tried the following, but it still does not work, so it is hoped that someone who has a better knowledge of Javascript will see an error. Please note that if is part of a larger authentication function that fires on the page - warnings were only there to find out if this got into it, if (that it isn’t) - when this block is removed, the rest of the JS on the page works great.

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;
}

- regexWordRule, js .

var regexWordRule = /[\S]+/;
+5
2

, , :

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 .

+2

MVC3, Remote validation (RemoteAttribute). ajax-.

.

+1

All Articles