Laravel

Laravel Mobile-Phone Number Validation Examples

Laravel is a popular PHP framework known for its simplicity and robustness. When building web applications, it's often necessary to validate user inputs, including phone numbers. In this article, we will explore two examples of mobile/phone number validation using Laravel's built-in validation features.

Example 1: Basic Digit Validation
In this example, we'll validate a phone number to ensure it contains exactly 10 digits.

$request->validate([
   'phone' => 'required|digits:10',
]);

Explanation:
- The `required` rule ensures that the `phone` field is not empty.
- The `digits:10` rule validates that the `phone` field contains exactly 10 digits.

Example 2: Regular Expression Validation
In this example, we'll validate a phone number using a regular expression pattern and a minimum length requirement.

$request->validate([
   'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
]);

Explanation:
- The `required` rule ensures that the `phone` field is not empty.
- The `regex:/^([0-9\s\-\+\(\)]*)$/` rule validates the `phone` field against the provided regular expression pattern. This pattern allows digits, spaces, hyphens, plus signs, and parentheses.
- The `min:10` rule specifies that the `phone` field must have a minimum length of 10 characters.

Leave A Comment