DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

4

Vaidating string for numeric, alphanumeric and alphabetic

Hi everyone! After lots of javascript blogs let's go back to csharp. Lots of time we have to deal with data in a string form and then we have to validity the string for its numeric or alphabetic form. Let's say we want to validate form input and we have some "Code" input field which should contain only numeric value. At the backend, we are receiving just a string and we have to validate the string for a numeric value. Obviously regular expression will be the first thing in our mind.🤔

Mostly some of us tries to avoid using Regex as compared to available built in function, including me😬

Checking string over numeric format

Approach 1

Char.isDigit() method is one of the approaches to go about. In C#, Char.isDigit() is a System.Char struct method that verifies if each Unicode character is a number.

Alt Text

Approach 2

Another way to check for numeric format is by using the TryParse() method. TryParse(string inputString, out double value) method tries to parse input string and if the value can be parsed then returns true and converts the value else it returns false.

Alt Text

Checking string over alphabetic format

Approach

If we want to validate a string for its alphabetic form then we can use Char.isLetter() method. Char.isLetter() is a System.Char struct method that verifies if each Unicode character is a number.

Alt Text

Checking string for alphanumeric format

Approach

If we want to validate a string over combination of alphabets and numbers then there is still an option of using Char.isLetterOrDigit() method. Char.isLetterOrDigit() is a System.Char struct method that verifies if each Unicode character is a letter or number.

Alt Text

Conclusion

If the code do not demands pattern matching but only determining data type then we can achieve it using Char struct methods.

Happy Coding!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay