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:
Fiddle here.