How to validate phone numbers with jQuery?

US Valid Phone number formats & Regex

Regex or regular expressions are one of the most popular phone number validation methods. Regular expressions have a long history in UNIX tools and programming languages like C# and JavaScript. 

In the simplest terms, regular expressions are a sequence of characters that define a search pattern. You can use Regex to search, edit and manipulate text, as well as perform validation.

The problem with regular expressions is that it can be difficult to verify that an expression behaves as you designed it to, especially if it is complex and/or generated by code. If you're doing something simple like checking for an alphanumeric string or a specific telephone number format, then regular expressions work fine. 

However,  you're trying to check for something more complex like a sequence of digits followed by a space and then 3 letters followed by another space and 2 digits, then your regular expression will get very complicated and it will be very easy to make a small typo in the Regex or in the code that generates the Regex, which could cause it to match incorrect values.

This can raise its own challenges as you’ll need to use a Regex pattern that can handle many different cases and area codes. 

A United States number can take the following forms:

  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899
     

If you need a stricter solution you will need Regex to handle these rules. Here is one such method using a Regex pattern

/^[\(\)\.\- ]{0,}[0-9]{3}[\(\)\.\- ]{0,}[0-9]{3}[\(\)\.\- ]{0,}[0-9]{4}[\(\)\.\- ]{0,}$/‍

This will check if your string is a valid telephone number and matches numbers against each part of the pattern. Let’s look at using a different jQuery approach to telephone number validation. 
 

Validate US phone number using jQuery

In cases like this, where you can write code to perform validation, using jQuery instead of using Regex is often simpler, easier to understand, less likely to contain bugs, and much easier to check against expected inputs and outputs.

jQuery offers an in-built option for validating a US number. In the additional-methods.js file, there are several telephone number validation methods you can use. Open this additional-methods.js file. There is a method called phone_number that takes an element as an argument, This callback function adds the validation we need.

The validator called phoneUS country code is what we need to use in this case. This rule also checks the length, so the additional arguments are redundantly unnecessary. 

You can perform validation by adding the following method to your code:


$(document).ready(function() {

  $('#myform').validate({
    rules: {
      phoneNumber: {
        phoneUS: true,
        required: true
      }
    },
    submitHandler: function(form) {
      alert('valid form');
      return false;
    }
  });
});

If the number is valid this code will return true else return false. Add the following code to your file to test our new function. The element phone_number can be used to test your validation.


form id="myform"
  input type="text" name="phone_number" / br/
  input type="submit" /
/form

When you enter a number into the text field that is not a valid phone number, it will return false and you will be shown a message: “Please specify a valid phone number”. 

You could also use this jQuery validate plugin. This external plugin can handle number validation elegantly and with little setup or effort required. 

Validate international numbers with jQuery

To check international numbers, you can use a similar approach to the one we just covered. You have two options:

  • Using Regex to validate an international telephone number.
  • Using in-built jQuery options. 

Let’s start with how to validate a UK phone number using jQuery.

UK phone number validation jQuery

Let’s look at what the format is for valid telephone numbers across the United Kingdom. This list was recommended from the official UK government website: 

  • 020 7946 0100
  • 020 7946 0866
  • 020 7946 973

These are not real numbers and can be used for testing. Find the full list of these numbers here. 

You can use the following Regex pattern to validate a UK number:

^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$‍

Non digits won’t be accepted by this pattern when the pattern match is performed. This Regex will flag any input that does not follow the formatting rules of UK numbers.

You can also use the in-built validator for UK numbers. The only difference is changing phoneUS to phoneUK. Check out the method in the code below:


$(document).ready(function() {

  $('#myform').validate({
    rules: {
      phoneNumber: {
        phoneUK: true,
        required: true
      }
    },
    submitHandler: function(form) {
      alert('valid form');
      return false;
    }
  });
});

Add the following HTML code to your file to test our new method, which will return true if the number is valid. The element phone_number can be used to test your validation.

Don’t stop at just your example, try implementing this element part of a larger project. Let’s look at some of the options available for validating an Australian number.

Australian phone number validation methods

According to the official Australian government website, Australian telephone numbers take the following format:

  • 02 1234 4321 - A landline number in NSW or the ACT
  • 0400 000 000 - A mobile number
  • 1300 975 707 - An Australia-wide landline number
  • 13 00 00 - An alternative Australia-wide landline number
  • +61 2 1234 4321 - An Australian landline number in international format
  • +61 400 000 000 - An Australian mobile number in international format
     

You can use the following Regex pattern to check an Australian number:

/^(?:\+?61|0)[2-478](?:[ -]?[0-9]){8}$/‍

This pattern will match an element against valid Australian numbers. Unlike the phone numbers for the United States and the United Kingdom, there is no in-built validation in jQuery for Australian phone numbers. This pattern will flag any invalid phone number that is entered.

jQuery Validate Phone Number Alternatives

jQuery validation is a popular method thanks to its in-built options and the jQuery validate plugin, but there are many alternatives to using jQuery for telephone number validation. One interesting option is this library offered by Google. You can access phone validation code for more than 200 countries for a number of different programming languages. 

Use this library in your code and implement it in a custom method of your own. 

API Phone Number Validation

Another excellent option is using an API to perform telephone number validation. The Phone Number Validation and Verification API offered by Abstract comes loaded with features such as:

  • Fake and invalid number detection,
  • Carrier and line type identification,
  • Support for 190 countries,
  • Compliance with Privacy standards (GDPR, CCPA).
     

When you implement this API you can improve your contact rate and clean your existing list of contacts making it an excellent option for checking whether an input is a valid phone number. That concludes this guide! If you enjoyed reading this far, check out this other post about How to do IP Geolocation in jQuery.

What is GEEK

Buddha Community

Hertha  Mayer

Hertha Mayer

1594769515

How to validate mobile phone number in laravel with example

Data validation and sanitization is a very important thing from security point of view for a web application. We can not rely on user’s input. In this article i will let you know how to validate mobile phone number in laravel with some examples.

if we take some user’s information in our application, so usually we take phone number too. And if validation on the mobile number field is not done, a user can put anything in the mobile number field and without genuine phone number, this data would be useless.

Since we know that mobile number can not be an alpha numeric or any alphabates aand also it should be 10 digit number. So here in this examples we will add 10 digit number validation in laravel application.

We will aalso see the uses of regex in the validation of mobile number. So let’s do it with two different way in two examples.

Example 1:

In this first example we will write phone number validation in HomeController where we will processs user’s data.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
                'name' => 'required',
                'phone' => 'required|digits:10',
                'email' => 'required|email|unique:users'
            ]);

        $input = $request->all();
        $user = User::create($input);

        return back()->with('success', 'User created successfully.');
    }
}

Example 2:

In this second example, we will use regex for user’s mobile phone number validation before storing user data in our database. Here, we will write the validation in Homecontroller like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Validator;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
                'name' => 'required',
                'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
                'email' => 'required|email|unique:users'
            ]);

        $input = $request->all();
        $user = User::create($input);

        return back()->with('success', 'User created successfully.');
    }
}

#laravel #laravel phone number validation #laravel phone validation #laravel validation example #mobile phone validation in laravel #phone validation with regex #validate mobile in laravel

How To Validate Phone Number Using Jquery Input Mask

In this small tutorial I will explain you how to validate phone number using jquery input mask, Using jquery input mask we can validate diffrent type of phone no with diffrent country code. Here, we are using jquery inputmask js for this example, so we can easily validate phone no.

This Article is Originally Published on Websolutionstuff : https://websolutionstuff.com/post/how-to-validate-phone-number-using-jquery-input-mask

<html>
<head>
    <title>jquery input mask phone number validation - websolutionstuff</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
</head>
<body>
  
<div class="container" style="border:1px solid red; padding: 0px 20px 20px 20px; margin-top: 20px;">
    <h1>jquery input mask phone number validation - websolutionstuff.com</h1>
  	<br>
    <strong>Phone Number:</strong>  
    <input type="text" name="phone" class="phone_number form-control" value="9876543210">
  	<br>
    <strong>Phone Number:</strong>  
    <input type="text" name="phone" class="phone_number_2 form-control" value="9876543210">
  	<br>
    <strong>Phone Number:</strong>  
    <input type="text" name="phone" class="phone_number_3 form-control" value="91 9876543210">
  
</div>
  
<script>
    $(document).ready(function(){
        $('.phone_number').inputmask('(999)-999-9999');
        $('.phone_number_2').inputmask('(99)-9999-9999');
        $('.phone_number_3').inputmask('+99-9999999999');
    });
</script>
  
</body>
</html>

In above code i have added inputmask in jquery for diffrent validation.

You can see output in below screen print.

How To Validate Phone Number Using Jquery Input Mask


Also Read : Google Map With Draggable Marker Example

#javascript #jquery #validation #phone #number #input-mask

How To Validate Password And Confirm Password Using JQuery

In this post I will show you how to validate password and confirm password using jQuery, Validation is basic and important feature for authentication user so here i will give you demo about password and confirm password validation using jquery.

In jquery we are using keyup event to check whether password and confirm password is match or not.

Read More : How To Validate Password And Confirm Password Using JQuery

https://websolutionstuff.com/post/how-to-validate-password-and-confirm-password-using-jquery

#javascript #jquery #validation #validate password and confirm password #validate password in jquery #validate password and confirm password in jquery

How To Check Password Strength Using JQuery

In this post I will show you how to check password strength using jQuery, here I will check whether password strength is fulfill min character requirement or not.

I will give you example how to check password size using javascript and jQuery password strength. password is most important part of authentication many times you can see error message like enter valid password or password must be at least 6 character etc. So, here we are check password using jquery.

How To Check Password Strength Using JQuery

https://websolutionstuff.com/post/how-to-check-password-strength-using-jquery

#jquery #how to check password strength using jquery #validation #how to check password size using javascript #jquery password strength #jquery password validation

I am Developer

1616903742

Form Validation using jQuery in PHP

Simple contact form submits in PHP MySQL with jQuery validation. In this tutorial, you will learn how to create a contact form in PHP, and how to submit form data into the MySQL database with jQuery validation.

This tutorial helps you step by step for creating or submit a contact forms in PHP MySQL DB with jQuery validation. And you can use this form for your business queries. The good thing is you can use this contact form in your web application too.

Contact Form Validation using jQuery in PHP

Just follow the few below steps and easily create and submit contacct form in PHP MySQL with jquery validation.

  • Step 1 - Create Table in Database
  • Step 2 - Create a Database Connection File
  • Step 3 - Create Contact Form in PHP

https://www.tutsmake.com/php-contact-form-with-jquery-validation-example/

#jquery validation in php registration form #simple jquery form validation example in php #jquery validation in php form