Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 576 Vote(s) - 3.44 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Verifying that a string contains only letters in C#

#1
I have an input string and I want to verify that it contains:

- Only letters or
- Only letters and numbers or
- Only letters, numbers or underscore

To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#?
Reply

#2
You can loop on the chars of string and check using the Char Method [IsLetter][1]
but you can also do a trick using String method [IndexOfAny][2] to search other charaters that are not suppose to be in the string.


[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#3
Only letters:

Regex.IsMatch(input, @"^[a-zA-Z]+$");

Only letters and numbers:

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

Only letters, numbers and underscore:

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");
Reply

#4
Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.
Reply

#5
Letters only:

Regex.IsMatch(theString, @"^[\p{L}]+$");

Letters and numbers:

Regex.IsMatch(theString, @"^[\p{L}\p{N}]+$");

Letters, numbers and underscore:

Regex.IsMatch(theString, @"^[\w]+$");

Note, these patterns also match international characters (as opposed to using the `a-z` construct).
Reply

#6
I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through