Jonathan Escobedo
Jonathan Escobedo

Reputation: 4063

Validate more than two words as minimum on asp:textbox

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!

Upvotes: 1

Views: 1170

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415931

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

Upvotes: 2

driis
driis

Reputation: 164321

Implement it as a custom validator. See https://web.archive.org/web/20210608194151/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.

Upvotes: 3

Related Questions