Block if you just type a word into a Textbox

Asked

Viewed 450 times

1

I work with C# - WPF and have a field where the client can enter his full name. I’d like to validate where it can’t just type the first name if it doesn’t open a blocking message. I mean, he would need to type at least two names.

I tried to do it this way, but he 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");
}

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

1 answer

4


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

  • String.Trim to delete spaces at the beginning and end of the string
  • String.Split to split 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 option StringSplitOptions.RemoveEmptyEntries is required for cases where the user inserts two or more spaces between words, eg: Diogo Castro.

Fiddle: https://dotnetfiddle.net/cIMd7f

  • Perfect explanation friend, and it worked perfectly... Thank you xDD

Browser other questions tagged

You are not signed in. Login or sign up in order to post.