Ensuring the accuracy of phone numbers with the power of AngularJS

Is there a way to ensure that the phone number input is always 10 digits long using AngularJS?

This is my attempted code:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
  <div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
    <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
    <div class="col-sm-9">
      <input type="number" 
             class="form-control" 
             ng-minlength="10" 
             ng-maxlength="10"  
             id="inputPhone" 
             name="phone" 
             placeholder="Phone" 
             ng-model="user.phone" 
             ng-required="true">
      <span class="help-block" 
            ng-show="registration.phone.$error.required && 
                     registration.phone.$error.number">
                     A valid phone number is required
      </span>
      <span class="help-block" 
            ng-show="((registration.password.$error.minlength || 
                      registration.password.$error.maxlength) && 
                      registration.phone.$dirty) ">
                      Phone number should be exactly 10 digits long
       </span>
    </div>
  </div>
</form>

Despite this, I am unable to get the validation error to work.

Answer №1

Give this a shot:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
    <div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
        <label for="inputPhone" class="col-sm-3 control-label">Telephone :</label>
        <div class="col-sm-9">
            <input type="number" 
                   class="form-control" 
                   ng-minlength="10" 
                   ng-maxlength="10"  
                   id="inputPhone" 
                   name="phone" 
                   placeholder="Telephone" 
                   ng-model="user.phone"
                   ng-required="true">
            <span class="help-block" 
                  ng-show="registration.phone.$error.required || 
                           registration.phone.$error.number">
                           A valid phone number is necessary
            </span>
            <span class="help-block" 
                  ng-show="((registration.phone.$error.minlength ||
                           registration.phone.$error.maxlength) && 
                           registration.phone.$dirty) ">
                           Telephone number should consist of 10 digits
            </span>

Answer №2

Take a look at this solution

Essentially, you have the option to construct a regex that meets your requirements and then apply that pattern to your input field.

Alternatively, for a more straightforward method:

<input type="number" required ng-pattern="<insert your regex here>">

For further information, refer to the angular documentation here and here (built-in validators)

Answer №3

Utilizing ng-pattern can ensure that mobile numbers start with 7, 8, or 9 and only contain digits. The mobile number should be exactly 10 digits long.

function validateMobileNumber($scope){
    $scope.onSubmit = function(){
        alert("Form submitted successfully");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div ng-app ng-controller="validateMobileNumber">
<form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter a valid mobile number!</span>
    <input type="submit" value="Submit"/>
</form>
</div>

Answer №4

You might want to consider utilizing the ng-pattern feature, which I personally believe is a best practice. In a similar fashion, you can explore using ng-message. Take a look at the ng-pattern attribute in the following HTML snippet. The code provided is only a portion, but hopefully, it gives you a good understanding.

angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
  $scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
  <div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
    <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
    <div class="col-sm-9">
      <input type="number" class="form-control" ng-pattern="ph_numb"  id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
      <div class="help-block" ng-messages="registration.phone.$error">
        <p ng-message="required">Phone number is required.</p>
        <p ng-message="pattern">Phone number is invalid.</p>
      </div>
    </div>
  </div>
</form>

Answer №6

I recently discovered a sleek and polished appearance by utilizing AngularUI Mask. It's incredibly user-friendly to set up and allows for customization of masks for various inputs. Pair it with a basic required validation and you're good to go.

Check out AngularUI Mask here!

Answer №7

<form id = "phoneForm">
    <div>
    <input type="tel"
           placeholder = "Please enter your phone number"
           class = "phonenumberInput"
           name = "phoneNumber"
           ng-minlength = "10"
           ng-maxlength = "10"
           ng-model="phoneNumber" required/>
           <p ng-show = "phoneForm.phoneNumber.$error.required ||
                       phoneForm.phoneNumber.$error.number">
                       Valid phone number is mandatory</p>
            <p ng-show = "((phoneForm.phoneNumber.$error.minlength ||
                        phoneForm.phoneNumber.$error.maxlength)
                        && phoneForm.phoneNumber.$dirty)">
                        Phone number must be 10 digits long</p><br><br>
       </div>
   </form>

Answer №8

Implement ng-pattern to validate a basic pattern of 10 numbers in this scenario. If the pattern does not match, an error message will be displayed and the button will be disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> Please enter a valid phone number</p>
        </div>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Search</button>

You can also utilize a more complex pattern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for validating complex phone numbers

Answer №9

<div ng-class="{'has-error': userInfoForm.phoneNumber.$error.pattern ,'has-success': userInfoForm.phoneNumber.$valid}">

              <input type="text" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^[7-9][0-9]{9}$/"  required>

In this case, the form name I am using is "userInfoForm".

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

Acquiring a property from an object that is specified within a function

I have created an object with properties inside a function: function createObject() { const obj = { property1: value, property2: value } } How can I access this object from outside the function? Would redefining it like ...

Implementing Firebase pagination alongside Mui-Datatable pagination and sorting capabilities

I've been trying to implement server-side pagination and filtering for the Mui-Datatable to display my data, but I haven't been successful so far. Here are the snippets of code that I have been working on: One issue that I'm facing is that ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Utilize an image in place of text (script type="text/javascript")

The vendor has provided me with some code: <a class="sh_lead_button" href="https://107617.17hats.com/p#/lcf/sfrnrskrvhcncwvnrtwwvhxvzkrvzhsd" onclick="shLeadFormPopup.openForm(event)">FREE Puppies</a> <script type="text/javascript" src="htt ...

Here are the steps to trigger a pop-up window in JavaScript that is filled with data fetched via an AJAX call:

I'm currently working on a java class where I need to insert a link into a table grid. This code is specific to the internal API of our company. /***MyCustomLink.java*********/ customLink.setOnClick( "fetchURL", return false;); addGridItem("cu ...

Tips for sending multiple pieces of data to an Arduino with NodeJS's serialport library

I am having trouble writing multiple data using the same port, but I see that node-serialport allows for reading multiple data functions simultaneously. How can I also write multiple data at the same time? This is how I have attempted it: - index.js- con ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

Using Angular's ng-repeat directive to create dynamic directives

Creating a comprehensive view with stacked rows filtered from a JSON array, resonating deeply with complex layering intricacies. Angular novices may find solace in directivizing simplicity while grappling with convoluted alternatives in real-world applica ...

Utilizing a material-ui button within a React application as the trigger for a Popup using MuiThemeProvider

I want to trigger a Popup in React using a button with a custom theme: <PopUp modal trigger={ <MuiThemeProvider theme={buttonTheme}> <Button variant="contained" color="secondary">Excluir& ...

I'm attempting to install the "firebase" package using npm, but I keep encountering a python-related error message during the installation process

I am experiencing difficulties while attempting to install the firebase package in a local expo-managed project. Unfortunately, I keep receiving the following error message... Here is the error message that I am encountering I have already tried using "e ...

How can I add header and footer elements in dot.js template engine?

My understanding was that all I needed to do (as per the documentation on GitHub) was to insert {{#def.loadfile('/snippet.txt')}} into my template like this: <!DOCTYPE html> <html> <head> <meta charset=&a ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Executing asynchronous JavaScript calls within a loop

I've encountered an issue with asynchronous calls in JavaScript where the function is receiving unexpected values. Take a look at the following pseudo code: i=0; while(i<10){ var obj= {something, i}; getcontent(obj); / ...

What is the order of reflection in dynamic classes - are they added to the beginning or

Just a general question here: If dynamic classes are added to an element (e.g. through a jQuery-ui add-on), and the element already has classes, does the dynamically added class get appended or prepended to the list of classes? The reason for my question ...

Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, ...

Example of a Single-Page Application using Angular 2

Currently working on a project to create a single page application. The layout will include a search section and a results section. export class AppComponent implements OnInit{ // Div visibility. searchVisible = true; resultsVisible = false; ...

why is my angular listing malfunctioning when I try to compare two fields?

<div ng-controller="SamsungServicesCtrl"> <ion-content> <li class="item item-checkbox" ng-repeat="item in items" > <img src="{{item.icon}}" style="float:left;height:30px;width:30px;padding-right:5px;" & ...

How can curly braces be utilized in an array reduce method?

If the function `fn3` is used instead of `fn2` in this code snippet running on node 9.5.0, the `console.log(totalUpvotes)` will display `undefined`. Shouldn't it actually be equal to 92? const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...