Validate a mobile number

EasyFunction Programs · 37 of 39

Write a Python function to check whether a mobile number is valid: 10 digits starting with 6, 7, 8 or 9 (optionally with +91).

Advertisement
Input
"9876543210", "+91 9123456789", "12345"
Output
9876543210 True
+91 9123456789 True
12345 False
5876543210 False

Approach

  1. A regular expression describes the pattern.

Solution

Python
import re def is_valid_mobile(number):    return bool(re.fullmatch(r"(\+91[\s-]?)?[6-9]\d{9}", number.strip())) for n in ["9876543210", "+91 9123456789", "12345", "5876543210"]:    print(n, is_valid_mobile(n))
Output
9876543210 True
+91 9123456789 True
12345 False
5876543210 False

Line by line

Line 4

fullmatch requires the whole string to fit, so extra characters fail.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs