Stop the user from entering anything other than numbers

I am working on a directive to only allow users to input numbers. Check out my implementation below.

Snippet from my directive template:

<input type="text" maxlength="5" ng-keypress="allowNumbers($event)">

Function in my directive:

$scope.allowNumbers= function (ev) {
    var key = ev.charCode || ev.keyCode || 0;
    var allowed = (
        key == 8 ||
        key == 9 ||
        key == 13 ||
        key == 46 ||
        key == 110 ||
        key == 190 ||
        (key >= 35 && key <= 40) ||
        (key >= 48 && key <= 57) ||
        (key >= 96 && key <= 105));

    return allowed;
};

During my debugging process, I encountered an issue where the value in the textbox was still being entered even if the function returned either true or false. Is there a way to prevent non-number key presses from being entered?

Answer №1

If you need to restrict input to numbers only, you can implement a directive in Angular:

angular.module('myApp', []).directive('numbersOnly', function(){
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (!inputValue) return ''
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }

                return transformedInput;
            });
        }
    };
});

Then you can use this directive in your input fields like this:

<input type="text" maxlength="5" numbers-only/>

By adding the numbers-only attribute, you can easily apply this behavior to any input field that requires it.

For a demonstration, you can check out this JSFiddle example.

Answer №2

To simplify this process and ensure compatibility with various forms of input (such as copy-paste), I would recommend the following approach:

<input type="number" ng-model="myNumber">

$scope.$watch('myNumber', function (input) {
    $scope.myNumber = input.replace(/\D/g, '');
});

Answer №3

    function CheckIfNumeric(event) {

var keyVal = event.keyCode == 0 ? event.charCode : event.keyCode;
var result = ((keyVal >= 48 && keyVal <= 57) || (specialKeys.indexOf(event.keyCode) != -1 && event.charCode != event.keyCode));
//  document.getElementById("error").style.display = result ? "none" : "inline";
return result;
}

Also in html

     <input type="text" onkeypress="return CheckIfNumeric(event);" />

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

Tips on sending arguments to functions associated with ...mapActions...()?

After analyzing the passage below export default { methods: { ...mapActions(["updateData", "resetData"]); } } I wanted to include a parameter in the called functions. Unsure of the proper way to do this while still using the ...mapAction() call, ...

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

`How can the background color be altered based on specific conditions?`

I am attempting to modify the background color. My goal is to change every odd result to a light green (#f0f5f5) to avoid a large white space when the result ends in an even number. I would also like to change the background color of the pagination section ...

BufferGeometry is not being displayed

After working extensively with BufferGeometry, I considered myself quite familiar with it. However, I am currently facing an issue while trying to create a simple square plane - there is no visible plane, no errors, and everything seems to be set up correc ...

Is there a way to retrieve a different value within the JavaScript code (imagepicker)?

I need help with setting up a page where users can choose an image to forward them to another page. However, I'm facing an issue when the user chooses two images at once. Can anyone provide ideas on how to handle forwarding in this scenario? You can c ...

What is the best way to utilize useClient in the code of my Next.js project?

I've been attempting to execute the code attached below, but I keep encountering an error stating that a component being imported requires useState and should only be used in a Client Component. However, none of its parent components are marked with " ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Is there a method in JavaScript/jQuery to gently push or flick the scroll so that it can be easily interrupted by the user? Further details are provided below

I am looking for a solution in javascript that will allow the page to automatically scroll down slightly, but I also want the user to be able to interrupt this scroll. When using jquery for auto-scrolling, if the user begins manual scrolling while the ani ...

ways to retrieve script template variable in angularjs application

I have written scripts to create a whiteboard using canvas inside the template page of AngularJS. Now I need to assign the values of the points[] variable to an AngularJS scope variable. <script> var points = []; </script> How can I access th ...

What could be the reason why readyState is not equal to 4?

I've been trying to figure out how to use Ajax to fetch data from a database, but I'm encountering some issues... The problem arises when I submit the query and nothing appears on the screen... I understand that this issue is related to the read ...

Mandatory input Angularjs 1.2 and Bootstrap 3

Unable to create a form field with red highlight for required items in updated AngularJS and Bootstrap 3. Looking for solution without writing CSS, using only Bootstrap 3. Here's my setup on Plunker. UPDATE: Replaced content below with comments' ...

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

Function utilizing variables parsed by Angular directive

I am currently working on a directive that I have created: feedBackModule.directive("responseCollection", ['deviceDetector', function (deviceDetector) { return { restrict: "E", templateUrl: 'js/modules/Feedback/direc ...

Creating a tailored regular expression for validating email addresses

Up to this point, I have crafted a regex pattern as Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$" that meets the following criteria: Not all characters should be numbers, ...

What is the most efficient way to establish a connection to "host:port" without relying on a web browser, utilizing only Node.js/JavaScript?

To establish a connection with a server (created using node js), we simply open the browser and include some code in a file like this: <script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script> <script type="text/javascript">/* ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...