Validating phone numbers in Saudi Arabia for both mobile and landlines

I've been struggling to validate a Saudi Arabia phone number on my Bootstrap form, but I keep running into an invalid error.

Here is the current regex pattern I am using:

/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/

function checkPhoneNumber(input) {
  let phoneNumber = input.val();
  let pattern = /^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/;
  if (pattern.test(phoneNumber)) {
    $(input).addClass('is-valid');
  } else {
    $(input).addClass('is-invalid');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<form class="needs-validation" method="POST" action="" onsubmit="checkPhoneNumber()">
  <div>
    <label for="contact_no1">Contact Number</label>
    <input id="contact_no1" name="contact_no1" type="tel" class="form-control" id="contact_no1" placeholder="" value="" required>
    <div class="invalid-feedback">
      Please enter a valid contact number.
    </div>
  </div>
</form>

Answer №1

Matching the numbers in this pattern is quite straightforward:

^((?:[+?0?0?966]+)(?:\s?\d{2})(?:\s?\d{7}))$

Answer №2

Using the RegExp Class makes pattern matching simple. Check out this example:

var regex = new RegExp(/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/);
regex.test('0501234567'); // returns true;
regex.test('0521234567'); // returns false;

Answer №3

My regular expression pattern is as follows:

(?:\+?0*?966)?0?5[0-9]{8}

Without any spaces, this pattern will match numbers such as:

966512345678
+966512345678
00966512345678
512345678
0512345678

If you need to standardize the number, you can capture the number 512345678 using this pattern:

(?:\+?0*?966)?0?(5[0-9]{8})

Then, you can append either 0 or 966 to the captured number.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protractor Problem with Asynchronous Calls

New to Protractor, I started by using multiple 'its' in my code. However, I later consolidated everything into one 'it', resulting in the following structure: var UI = require('./../ui.js'); var co = require('co'); ...

What is the best way to align HTML inputs within a grid, whether it be done automatically or manually using JavaScript?

Arrange 20 HTML inputs with various data types into grid-columns as the user inputs data. Ensure that the grid container has div elements correctly positioned for output. ...

List of nested HTML tags in Javascript

I have been tasked with creating a specific HTML structure: <div id="dcontent"> <ul class="thm"> <li><a href="#"><img src="img/theme1.jpg" id="t1" border="none"/></a></li> <li><a href= ...

FormView does not have a defined namespace prefix asp - How should I specify my Page Directive?

After creating a basic web page using Microsoft Expression Web 4 with an ASP Connection to a local Access DB, I encountered an error when navigating to the page from another webpage. The browser displayed the following errors: Error: Namespace p ...

Using jQuery to dynamically populate a list with the information from a JSON dataset

How can I utilize JSON data to ensure that jquery populates the correct ul in this code snippet, creating 5 ul and populating them with li elements? Expected output: The slides should be assigned to specific modules as indicated in the JSON data, instead ...

NuxtLink sending users to incorrect destination URL

I am facing an issue with my static generated Nuxt site. Everything works perfectly fine when I host it locally, but once I load it on GitHub Pages, the NuxtLink elements' hrefs are incorrect. For instance, one of my links looks like this: <NuxtLi ...

Looking to insert an icon into the placeholder?

I am trying to insert a location icon into the placeholder of a label in a React component. <label> Places <input className="p-2" ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

What is the process for retrieving the result of a promise at a later time?

var screencastId = 'abc' var a = youtube.get(screencastId); a.then(function(screencast) { // Great, the screencast information is now available. console.log(screencast); }); // How can I access the `screencast` variable below? connection.be ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

A function designed specifically for parsing and manipulating hyperlinks within dynamically added content using jQuery

I have a unique one-page layout All my content "pages" are stored in separate divs, which are initially hidden using jQuery When a menu item is clicked, the inner content of the page holder is dynamically switched using html() However, I am facing an is ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

The submit button remains disabled even after verifying all the required fields

I have a registration form with basic customer details and a Submit button. I have successfully validated all the fields using Ajax, except for the Confirm password field which is being validated using JavaScript. The issue I am facing is that when I val ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). https://i.sstatic.net/NcJWU.png ...

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

JavaScript and Responsive Design Techniques

I'm struggling to create a responsive page that starts with a mobile-first approach, but I keep running into the same issue. When I have my dropdown menu in the mobile version, it looks good. However, when I try to switch it to the non-mobile version ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...