Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Verifying that a string contains only uppercase letters and numbers in C#

I would use Char.IsLetterOrDigit but I need the letters to be uppercase only.

I can’t seem to find a way to combine Char.IsLetterOrDigit and Char.IsUpper because digits won’t be allowed when I try this way:

if (input.All(Char.IsLetterOrDigit) && input.All(Char.IsUpper))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I missing something here?

How can I check each letter separately?

>Solution :

All() takes a predicate which can be a lambda expression. You can use this to check IsLetter && IsUpper separately from IsDigit.

input.All(c => (Char.IsLetter(c) && Char.IsUpper(c)) || Char.IsDigit(c))

Try it online

Alternatively, you could use a regular expression that matches zero or more uppercase characters or digits:

using System.Text.RegularExpressions;

Regex r = new Regex(@"^[A-Z0-9]*$");
r.IsMatch(input);

Try it online

Regex explanation:

^[A-Z0-9]*$
^               Start of string
 [A-Z0-9]       The uppercase letter characters or the digit characters
         *      Zero or more of the previous
          $     End of string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading