-
Notifications
You must be signed in to change notification settings - Fork 87
/
MobileNumberValidation.java
34 lines (30 loc) · 1.3 KB
/
MobileNumberValidation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MobileNumberValidation {
public static void main(String[] args) {
String phoneNumber = "+1234567890"; // Replace with the mobile number to validate
boolean isValid = validateMobileNumber(phoneNumber);
if (isValid) {
System.out.println("Mobile number is valid.");
String countryCode = extractCountryCode(phoneNumber);
System.out.println("Country Code: " + countryCode);
} else {
System.out.println("Mobile number is invalid.");
}
}
// Function to validate a mobile number with a country code
public static boolean validateMobileNumber(String phoneNumber) {
String regex = "^\\+\\d{1,}$"; // Pattern for a country code followed by digits
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(phoneNumber);
return matcher.matches();
}
// Function to extract the country code from a valid mobile number
public static String extractCountryCode(String phoneNumber) {
if (validateMobileNumber(phoneNumber)) {
return phoneNumber.substring(1); // Remove the '+' sign to get the country code
} else {
return "Invalid mobile number";
}
}
}