Sometimes, we need to remove all special characters from a mobile number and store just numbers only. The simplest way to do so is, look for the special characters and remove them from the number.
Here is a method that removes special characters, space, +, and - from a number. You can use the same approach to remove any character a number. If your string has other characters, add them to this list.
  1. private string convert_to_number(string No)
  2. {
  3. string mobileno = "";
  4. //remove special characters
  5. foreach (char ch in No)
  6. {
  7. if (ch != ' ' && ch != '+' && ch != '-')
  8. {
  9. mobileno = mobileno + ch.ToString();
  10. }
  11. }
  12. //convert to 10 digit
  13. if (mobileno.Length > 10)
  14. {
  15. mobileno = mobileno.Substring(mobileno.Length - 10, 10);
  16. }
  17. return (mobileno);
  18. }
Another way to validate a mobile number is to use a regular expression. Here is the mobile number validation regular expression:
  1. Regular expression:
  2. / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)
  3. /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)
  4. ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)
Here are more detailed tutorials on the same:
List of Most Common Regular Expressions and Their Usage
Top C# Regex Code Examples