Block if you enter only one word in a TextBox

1

I work with C # - WPF and I have a field where the client can enter their full name. I would like to validate where it can not enter only the first name if it does not open a blocking message. That is, he would need to enter at least two names.

I tried to do this, but it only takes the spaces that come before the first name

bool espaco= txtBox1.Text.Length>0 && txtBox1.Text.Trim().Length==0;

if (espaco){
    MessageBox.Show("Erro");
}

I can understand, otherwise I try to explain better ... Help me

    
asked by anonymous 28.04.2015 / 14:47

1 answer

4

To count the number of words (names) in the string, use:

  • String.Trim to delete spaces at the beginning and end of the string
  • String.Split to divide the string into a word collection
  • Array.Length to count the number of words


var wordCount = txtBox1.Text
                       .Trim()
                       .Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries)
                       .Length;

if (wordCount < 2){
    MessageBox.Show("Erro: insira o nome completo.");
}

The StringSplitOptions.RemoveEmptyEntries option is required for cases where the user enters two or more spaces between words, eg Diogo Castro .

Fiddle: link

    
28.04.2015 / 14:51