سؤال

I was wondering is there any way to make sure that a user enters both numbers and letters into a textbox and if not prompt a message? I have it as follows:

if(!Regex.IsMatch(string, @"^[a-zA-Z]+$") && !Regex.IsMatch(string, @"^[1-9]+$"))
{  
    MessageBox.Show("Please Enter both numbers and letters");
    return;
}

So what I tried to say here is that if the string doesn't have a letter AND if the string doesn't have a number, prompt an error. But, if you enter all letters (or numbers), no error prompts so I was wondering if there was a way to do this. I researched in the questions and didn't find anything apart from just how to allow certain characters.

هل كانت مفيدة؟

المحلول 2

What you want to do is to show the message if the string doesn't have any letters OR it doesn't have any numbers.

You don't need a regular expression for that either:

if(!str.Any(Char.IsLetter) || !str.Any(Char.IsDigit)) {  
  MessageBox.Show("Please Enter both numbers and letters");
  return;
}

Note: Chech the specification for Char.IsLetter so that the set of characters is acceptable for what you want to do.

نصائح أخرى

At the moment, your code says

Show the message if the string is not entirely made of letters, and not entirely made of numbers

which is almost the exact opposite of what you're after.

To fix it, you need to change "not entirely made of" to "doesn't contain", and "and" to "or":

if(!Regex.IsMatch(string, @"[a-zA-Z]") || !Regex.IsMatch(string, @"[1-9]"))
{  
    MessageBox.Show("Please Enter both numbers and letters");
    return;
}

The regular expressions now look for only a single letter or number, and the and is now an or.

If you want to make sure your input only contains letters any numbers, you could do the following as a separate step:

if(Regex.IsMatch(string, @"[^a-zA-Z0-9]"))
{  
    MessageBox.Show("Please Enter only numbers and letters");
    return;
}

Think simple:

[a-zA-Z0-9]+ is the regex you might want to try.

[a-zA-Z0-9\s]+ is the regex with spaces allowed between words/numbers.

Try your regex here: http://regexhero.net/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top