views:

171

answers:

2

Hello I want to validate the input, so the method for count words is the following :

public static string validateisMoreThanOneWord(string input, int numberWords)
        {
            try
            {
                int words = numberWords;
                for (int i = 0; i < input.Trim().Length; i++)
                {
                    if (input[i] == ' ')
                    {
                        words--;
                    }
                    if (words == 0)
                    {
                        return input.Substring(0, i);
                    }
                }
            }
            catch (Exception) { }
            return string.Empty;
        }

Where I put this method, so when the method return empty after the validation, the page wouldnt postback (like RequireFieldValidator on AjaxToolKit)

Thanks!

+3  A: 

Implement it as a custom validator. See http://aspnet.4guysfromrolla.com/articles/073102-1.aspx for an example

If you wan't it to work without postback, you should also implement the clientside version of the validation in Javascript. You could have the clientside version make an AJAX call to the C# implementation, but it is fairly simple logic - So I would choose to implement it in Javascript and save the user an AJAX request.

driis
+1  A: 

First of all, you can simplify that a lot:

public static bool validateIsMoreThanOneWord(string input, int numberWords)
{
    if (string.IsNullOrEmpty(input)) return false;

    return ( input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length >= numberWords);    
}

This version also has the advantage of being easy to extend to include other whitespace like tabs or carriage returns.

The next step is that you can't stop the page from posting back with server-side code alone. Instead, you need to use a CustomValidator and write some javascript for it's ClientValidationFunction, which would look something like this:

var numberWords = 2;
function checkWordCount(source, args)
{         
   var words = args.Value.split(' ');
   var count = 0;
   for (int i = 0; i<words.length && count<numberWords;i++)
   {
      if (words[i].length > 0) count++;
   }
   args.IsValid = (count >= numberWords);
   return args.IsValid;
}
Joel Coehoorn