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.
- private string convert_to_number(string No)
- {
- string mobileno = "";
-
- foreach (char ch in No)
- {
- if (ch != ' ' && ch != '+' && ch != '-')
- {
- mobileno = mobileno + ch.ToString();
- }
- }
-
- if (mobileno.Length > 10)
- {
- mobileno = mobileno.Substring(mobileno.Length - 10, 10);
- }
- return (mobileno);
- }
Another way to validate a mobile number is to use a regular expression. Here is the mobile number validation regular expression:
- Regular expression:
-
- / ^((\+){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)
-
- /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)
-
- ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)
Here are more detailed tutorials on the same: