Prevent the use of the + or - symbols within the body of a regular expression when

function validateNumberInput(){
        userInput = document.getElementById('txtNumber').value;
        var numberPlusMinusRegex = /^[\+?\-?\d]+$/g;

        if (userInput.match(numberPlusMinusRegex)) {
            alert('Valid input');
            return true;

        }
        else {
            alert('Invalid input');
            return false;

        }

}

Check out this JsFiddle link for more

I have created a function to validate user input allowing only numbers and +,- signs. However, I am struggling with restricting the input in the middle where only +,- at the end is allowed but not in the middle.

Answer №1

Adding the symbols \+?\-? into the character class allows for the presence of +, -, or ? within the string.

If you want to permit a + or - at the beginning and end of the string, use

/^[-+]?\d+[-+]?$/
  ^^^^^   ^^^^^

The [-+]? matches either + or - occurring zero or one time (due to the ? quantifier).

Alternatively, if the signs are only allowed at the start OR only at the end, utilize

/^([-+]?\d+|\d+[-+]?)$/

Explanation of the pattern:

  • ^ - denotes the start of the string
  • ( - Group initiation
    • [-+]? - represents 1 or 0 instances of - or +
    • \d+ - signifies 1 or more digits
    • | - or
    • \d+ - indicates 1 or more digits
    • [-+]? - stands for 1 or 0 occurrences of - or +
  • ) - marks the conclusion of the group
  • $ - specifies the end of the string.

Furthermore, it's recommended to employ RegExp#test for checking if a string adheres to a specific pattern rather than using String#match:

var NumberplusminusRegex =/^[-+]?\d+[-+]?/;
if (NumberplusminusRegex.test(charTyped)) { // Returns yes or no

function btnNumber(){
charTyped=document.getElementById('txtNumber').value;
    var NumberplusminusRegex =/^[-+]?\d+[-+]?/;    // REMINDER: Avoid using /g with RegExp.test()
    if (NumberplusminusRegex.test(charTyped)) {     // Check for match
        alert('yeah');
        return true;
    }
    else {
        alert('whoa');
        return false;
    }
}
<button onclick="btnNumber()">Click me</button>
<input type='text' id='txtNumber'/>

Answer №2

Check out this regex pattern

const NumberPlusMinusPattern = "/^[+-]?[0-9]+$/g";

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 best way to retrieve the value from a textfield in one module and use it in a

How can I access the value of a textField in another module within React.js without importing the entire textfield component? What is the most effective approach to get access to the value variable in a different module? Below is a sample functional textF ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

Incorporate an assortment of facial features into BufferGeometry using three.js

If I have a BufferGeometry, I can easily assign its vertices using an array of type Float32Array with the following code snippet: geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); However, is there a way to set the f ...

Updating the angular $resource method

I need to customize the query()-method of AngularJS $resource by using a custom $http-GET. However, it doesn't seem to be overriding the operation correctly. The result I am getting is an object with method, data, and headers, instead of data.rows[]. ...

Issues with the Jquery feedback plugin's functionality are currently preventing it

I wanted to incorporate a feedback feature into my web application. To do this, I searched on Google and found a suitable jQuery plugin. I followed the documentation provided by the plugin, including the library in my HTML file, and then wrote the code as ...

Display a new view upon clicking a button using AngularJS in a single-page web application

I am completely new to AngularJS and currently working on my first project. I apologize in advance if my question seems very basic. In my project, I have created a page using simple HTML with three buttons. When these buttons are clicked, I want to load v ...

Lagging speeds in client-side template rendering using Rivets.js

I have a function that renders an array of around 1000 objects, but the html bindings are causing significant performance issues. It currently takes about 5 seconds to complete rivets.bind(). Does anyone have any recommendations for improving performance? ...

There was a problem establishing a WebSocket connection to 'ws://127.0.0.1:2000/'. The attempt failed with the following error: net::ERR_CONNECTION_REFUSED

I have integrated websocket functionality using a repository found at https://github.com/kishor10d/CodeIgniter-Ratchet-Websocket After successfully testing the websocket on my local environment, I encountered issues when uploading the files to the live se ...

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

JQuery and PHP: Saving a rearranged set of divs in a form

Although I've searched for similar questions, none seem to address my specific issue. My problem involves a form with divs generated from a JSON array saved in a separate file. To style the form, I'm using Bootstrap and implementing JQueryUI&apo ...

What's the best way to implement a conditional header in React?

I am looking to create a conditional display of the Header based on different pages. Specifically, I want the Header to be hidden on the Home page and shown on other pages like posts page, projects page, etc. I have been brainstorming possible solutions f ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

IE11 does not properly redirect URLs after using window.location.reload(true)

Whenever the session expires, I make a call to the server using window.location.reload(true). After clicking the button, the server is contacted to retrieve details. However, in Internet Explorer 11, the URL does not change in the browser and the same page ...

struggling to retain data within scope when utilizing localstorage in angular

Currently, I am utilizing the fileReader to read a file, save the image in localStorage, and then display it on the view. In the controller: angular.module('App')controller('publsherProfileEditCtrl', ['$rootScope', '$sc ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

The Bootstrap Tooltip seems to be glued in place

Utilizing jQuery, I am dynamically generating a div that includes add and close buttons. Bootstrap tooltips are applied to these buttons for additional functionality. However, a problem arises where the tooltip for the first add button remains visible even ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...