AngularJS Regex for detecting numbers

I need to implement regular expressions in AngularJs that will accept the following three statements:

09344542525 -> 11 digit number starting with 09

02144532363 -> 11 digit number starting with 021

44532363 -> 8 digit number

Below is my HTML :

<div class="container co-operate" ng-controller="cooperationController">
    <form novalidate name="cooperationForm" class="signinform">
        <div class="form-group inner-addon right-inner-addon">
            <label class="form-label control-label"></label>
            <input ng-model="restaurantInformation.tel" type="text" name="tel" id="tel" placeholder="phone number"
               ng-pattern="mobRegEx || prePhoneRegEx || phoneRegEx" class="form-control default-input singleline-input" required />
            <span class="form-icon icon icon-avatar"></span>
        </div>
        <p ng-show="cooperationForm.tel.$error.pattern" style="color: red">Wrong number format</p>
    </form>
</div>

Angular:

app.controller('cooperationController', function ($scope) {
    $scope.mobRegEx = '/09[0-3][0-9]{8}/';
    $scope.prePhoneRegEx = '/021[0-9]{8}/';
    $scope.phoneRegEx = '[0-9]{8}';
    .
    .
    .
}

Currently, even after inputting an integer and testing it, the error paragraph always shows an error. Any suggestions on modifying the regular expression?

Answer №1

The combination of all three:

/^(?:0(?:21|9[0-9]))?[0-9]{8}$/

Explanation

  • ^ indicates the start of the string
  • (?:..)? is a group that can be optional, matching
    • 0(?:21|9[0-9]) either "021" or...
    • 09 followed by another digit
  • [0-9]{8} matches eight more digits
  • $ represents the end of the string

I included ^ and $ anchors to prevent matching substrings.

Answer №2

When attempting to utilize multiple regular expressions within the ng-pattern attribute by separating them with pipes, it is important to note that this is not considered valid. Instead of this method, it is recommended in a provided answer found at here, to either create a custom directive (such as ng-phone-number) or consolidate all individual expressions into a single pattern.

The implementation of a directive is likely to be the most effective choice for long-term maintainability.

Answer №3

let phoneNumber = /(+09|021|44532363)\d{1,12}/g; let phoneNumbersFound = inputValue.match(phoneNumber); console.log(phoneNumbersFound)

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

Gather information on LinkedIn connections

Looking to extract data from LinkedIn, specifically the connections of my own connections. I've successfully developed a Python script using BeautifulSoup and Selenium that is able to access the profiles of my connections and scrape their first 10 con ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

Angular 2: Change Boolean value depending on a condition

I find myself facing a challenge with a search-bar feature. My goal is to display all the filtered names when the input value reaches a length of 2 or more characters. After successfully extracting the value.length from the input field, I encountered a ro ...

Using JavaScript, enter the value into the input field and then redirect the

I'm encountering a minor issue with my contact form and jQuery redirection based on input fields. Everything was working smoothly until I attempted to integrate the redirection into the form validation code. Redirection snippet: $("#signup").submit ...

Next JS is trying to access a JSON file that does not exist

After setting up a route "/es/servicios" and configuring it in next.config.js: module.exports = { async redirects() { return [ { source: '/', destination: '/es', ...

I need assistance on updating a document in MongoDB using Node.js

I'm in the process of developing a feature that automatically updates a player's high score to their account when they achieve a new record. However, I'm struggling with how to search for a player by name and update their tag using mongoose. ...

The ng2-chart linechart will only display the first value that is added

My line chart is experiencing a strange issue where only the first value added after the initial values will display properly. Subsequent values are getting cut off for some reason. https://i.sstatic.net/pjW9y.png Although I have checked out a similar is ...

Is there a way to duplicate items similar to MS Word by using a combination of ctrl + mouse click +

In my fabricjs application, I currently clone an object by clicking ctrl + left mouse click on it, which works fine. However, I would like to be able to clone the object in a similar way to MS WORD, by using ctrl + click + drag. Has anyone achieved this f ...

Using JQuery with ASP.NET buttons

I am having trouble getting a jQuery function to fire in an ASP.NET button. It doesn't seem to be triggering. What could be the issue? //Code <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type= ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

Optimizing Three.js for better performance

Recently, I delved into working with three.js and webgl for a personal project. My goal was to develop a wardrobe model based on user input. You can check out the project at this link: Initially, the rendering speed was fast and smooth without Materials a ...

Managing multiple Socket.io connections upon page reload

I am currently developing a real-time application and utilizing Socket.io for its functionality. At the moment, my setup involves receiving user-posted messages through the socket server, saving this data to a MySQL database via the controller, and then b ...

Adjustable Pop-up Modal

I am attempting to implement a resizable modal window feature by utilizing increase and decrease icons. Additionally, I aim to have the modal centered on the screen following each click of increase/decrease. Thus far, only the increase functionality is fu ...

Setting up Oauth2 OIDC in an Angular 8 application

I've been attempting to set up OAuth2 in my Angular project for user login. I followed the documentation, but whenever I try to log in, it keeps showing an Unauthorized error and I'm not sure how to resolve it. Here are my configurations: auth c ...

Displaying a dynamic map with real-time coordinates sourced from a database using a combination of ajax and php

I'm currently facing an issue where my solution to retrieve coordinates for a specific place from a database and display a map centered on them is not working as expected. The problem seems to be arising because the map is being initialized without an ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

AngularJS - Embedding input fields within an HTML table within a form

The system is up and running now... I retrieve an array and insert the name into an input field. Then, I update the name in the input field and send it back using a PUT request. Here is the HTML code: <form id="edit"> <table> < ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...

Detecting page load status in Selenium WebDriver with Java by comparing two elements: a step-by-step guide

Challenges of Scaping a Table using Selenium WebDriver/Java In my current project, I am utilizing Selenium WebDriver/Java to extract data from a table. This table is spread across multiple pages, each requiring a click to navigate to the next one. At the ...