Verify whether the field includes a minimum number of numerical digits

I am currently using this script to validate whether a field is empty or not. The script works well for me, but I would like to add a condition that the field must contain at least 10 digits (numbers). If it doesn't meet this requirement, I want to display an error message as shown in the script. Can anyone help me figure out what needs to be added to the code below?

function checkIfBlank() {

var errorMessage = "";

    if (document.getElementById('phoneNumber').value == "") {
        errorMessage += "Your phone number must contain 10 digits.";
        document.getElementById('phoneNumber').style.borderColor = "red";
    }

    if (errorMessage != "") {
        $(".error-messages").text(errorMessage).fadeIn();
        return false;
    }

}

Answer №1

Eliminate any characters that are not numbers and determine the total count of digits

'x1y234z567k890---'
    .replace(/[^\d]/g, '') // "1234567890"
    .length;               // 10

Answer №2

If you are looking to validate a field for length on submission and it should only contain digits, you can utilize the following code snippet.

function checkPhoneNumber() {

    var errorMessage = "";
    var inputVal = document.getElementById('telefoonnummer').value;
    if (inputVal == "") {
        errorMessage += "Your 10 digit phone number is missing. ";
        document.getElementById('telefoonnummer').style.borderColor = "red";
    } 
    else if (inputVal !== "" && inputVal.length !== 10) {
        console.log("error");
        //set your error message here
    } 
    else {
        console.log("success");
    }

    if (errorMessage !== "") {
        $(".error-messages").text(errorMessage).fadeIn();
        return false;
    }

}

Update: Modified Version based on OP feedback - JSFiddle Link

Answer №3

    //checking whether the input is a number or not------
    function verifyInput(event, value){//utilize this function during keyup event of your field
    if(value.length <= 10) //check if it is up to 10 digits
    {   
    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
                     // Allow: Ctrl+A
                    (event.keyCode == 65 && event.ctrlKey === true) || 
                     // Allow: home, end, left, right
                    (event.keyCode >= 35 && event.keyCode <= 39)) {
                         // allow these keys, no action needed
                         return;
                }
                else {
                    // Confirm that it is a number and prevent the keypress
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                        event.preventDefault(); 
         }

                       }   
                    }
            }

implement the code with your text field like so

<input type="text" id="phone" onkeyup = "verifyInput(event,this.value);" />

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

Identifying rectangular shapes in an image and overlaying a div on top using Jquery

I am currently exploring the possibility of achieving the following: Imagine having an image within a div (serving as the background image). This image resembles an Excel sheet. My goal is to generate an input tag or contenteditable div when a user clicks ...

How come I'm facing difficulties when trying to send a post request to my WebApi using AngularJS's POST method?

I've uploaded "mytest.html" to the IIS server, and this project consists of WebApi and AngularJS. However, I am unable to make a correct request to my WebApi. I'm not sure why? 【HTML Code Snippets】 <!DOCTYPE html> <html> ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Guide on transferring href parameter from the parent Vue component to the child component

Hey there! I've been working on creating a Vue page, breaking it down into components, and populating it with content from json. It all seems pretty straightforward, but I've hit a snag. Why is the href parameter not showing up in the right place ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button. ...

Bootstrap Table encountering issues when displaying JSON data from Ajax response

I am currently struggling with an unusual issue. I have received a successful JSON response from the server, which I need to display in my Bootstrap Table. However, I am facing difficulty in displaying the JSON data in the Bootstrap Table while using AJAX ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

Retrieve data from a div element on a webpage using specific parameters

As I work on a form that includes various filters and a "Start" button in C# / ASP.NET MVC, my goal is to display database data in a partial view using Ajax when the button is clicked, based on certain parameters. Within this partial view, there is a link ...

Top storage solution for ExpressJS in the world of NodeJS

Embarking on the journey of creating my first substantial NodeJS application. My primary focus is achieving top-notch performance as the project involves a large AJAX (AngularJS) interface with numerous requests from multiple users. Currently in the proce ...

The mystery of why gulp-watch fails to remove files

I need help figuring out why my gulp-watch task isn't deleting files from the /dest directory when I delete them from /src. Can someone spot the issue? var watch = require('gulp-watch'); var imagemin = require('gulp-imagemin'); ...

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...

Is it possible to customize the width of text color alongside a progress bar?

My Bootstrap 4 Website contains the following HTML code snippet: <div class="container"> <div class="row"> <div class="col-md-6 mx-auto> <h2>Example heading text</h2> <h6>Example subh ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

Adding content into a designated position in a document

My challenge is to find the index of user-provided data in order to insert new data at that specific point. I am familiar with array insertion methods, but extracting the index provided by the user is where I'm stuck. My current approach involves filt ...