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

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Maintaining the greenery of AngularJS HTML code

Whenever I include ng-options in a select element, the options displayed end up looking like this: <select name="folderId" data-ng-model="message.folderId" data-ng-options="folder.id as folder.name for folder in folders"> <option value="" class= ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Ways to hide the dropdown when clicking away from the menu in angularjs

Whenever I click on an item, a dropdown menu appears. Clicking again on the item hides the dropdown. But now, I want to make the dropdown disappear if I click anywhere else on the window. Here's the code snippet: <div ng-click="showDropDown()" cl ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Implementing relative pathing in front-end development while using ExpressJS for the back-end

I'm currently in the process of developing an application with Express 4.14. When it comes to routing, I have a situation where the incoming request is "https://example.com/page", and I am using res.sendFile(__dirname + "/../client/pages/page/index.ht ...

Transform a nested array of objects into a distinct set of objects based on the data in JavaScript or TypeScript

I have a unique situation where I am dealing with a double nested array of objects, and I need to restructure it into a specific array format to better align with my table structure. Here are the current objects I'm working with and the desired resul ...

Encountering a 500 server error while trying to send an email using SendGrid in conjunction

Seeking help on integrating an email capture form into a NextJS site by following this tutorial: Simplified the form to only include the email field. The content of my api/contact.js file is as follows: const mail = require('@sendgrid/mail'); ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Changing the boolean value of User.isActive in Node.js: A step-by-step guide

Define a User Model with isActive as a Boolean property. Upon clicking a button, the user is redirected to a route where their information is retrieved based on the id from the parameters. Once the user is found, the script checks the value of isActive. ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

progressive selection modifying designs

Stumbled upon a demo at angularjs: cascade dropdown - see it here <link href="http://jsfiddle.net/6eCZC/1/">demo</link> Does anyone know how to incorporate html-templates based on the selection? ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

Creating a JSON object using various inputs through AngularJS

Just starting out with Ionic, Angular, and Firebase. This might be a silly question :) I'm working on an app using Ionic + Firebase, and I want to create a JSON object from multiple inputs. The interface looks like the image below: https://i.stack.i ...

Place form at the center of the Bootstrap Modal

My question is, how can I center the entire form, including the input fields and labels, within the modal? Here is also a helpful Fiddle: http://example.com, although the snippet provided should work as well. <script src="https://example.com/bootstr ...

Simple way to retrieve the first and last date of the current month using Node.js

I need help with retrieving the first and last date of the current month using the code below:- let currentDate = new Date(); let month = currentDate.getMonth() + 1; console.log(month); let firstDate = new Date(currentDate.getFullYear(), currentDate.getMon ...