DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

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!

Oldest comments (0)