Using a minus sign to denote negative values and leading zeroes to indicate positive values in regular expressions

I need help with a unique form validation requirement using regex. The values must be integers between -168 and 10688, where negative values range from -168 to -10688. What makes this challenging is that users must include leading zeros, with 4 characters required for negative values and 5 characters for positive values. For example, -023 is valid, as well as 00000 and 00345. However, 0, 000, and -000 are not valid. Can someone please assist me in implementing this regex validation? I'm worried it may be too complicated. Your help is greatly appreciated! ;(

Answer №1

This solution should meet your needs

^(\d{5}|\-(?!000)\d{3})$

Akxe is accurate in pointing out the acceptable maximum and minimum values. Regular expressions are specifically for validating strings, so they do not support mathematical functions. To ensure validation, you can either use JavaScript on the client side or handle it on the server side.

Answer №2

I found a pattern that fits the description you provided:

(-[1-9]\d\d|-\d[1-9]\d|-\d\d[1-9]|\d{5})

It gets tricky when excluding -000, leading to 4 different cases:

-[1-9]\d\d # negative numbers with a non-zero first digit
-\d[1-9]\d # negative numbers with a non-zero second digit
-\d\d[1-9] # negative numbers with a non-zero third digit
\d{5} # positive numbers with exactly 5 digits

However, keep in mind that this pattern doesn't account for upper/lower bounds. Those details can be handled easily with programming languages, and a regular expression isn't necessarily designed for that purpose.

Answer №3

J.A.'s solution (

(-[1-9]\d\d|-\d[1-9]\d|-\d\d[1-9]|\d{5})
) is accurate, however, it's important to consider adding the min and max attributes to the input field. Additionally, for a smoother user experience, consider automatically adding leading zeros. Just a friendly suggestion.
PS.: How does this relate to angular?

Answer №4

Here is a solution that I believe will be effective:

[0-9]{2}(-|[0-9]{3})

Explanation:

NODE                     DESCRIPTION
--------------------------------------------------------------------------------
  [0-9]{2}                match any numerical digit between 0 and 9, exactly 2 times
--------------------------------------------------------------------------------
  (-|[0-9]{3})            match either '-' OR any numerical digit between 0 and 9, exactly 3 times

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

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...

Restrict dropping items in HTML5 by only allowing the drop if the target div is

I am working on developing a user-friendly visual interface for creating simple graphics. The interface includes 10 image icons and 5 boxes where users can place these icons. Users have the freedom to select which icon they want to display and arrange them ...

attempting to eliminate on-screen buttons by hovering over the video

Is there a way to make my video play on loop like a GIF without the controls ever showing? I want it to have a seamless playback experience. Any ideas would be appreciated. P.s. Don't worry about any StackOverflow errors when running the snippet. Than ...

Tips for Guaranteeing the Installation of Mobile Web App on Device Only

Currently, I am developing a mobile web application using AngularJS and preparing to launch it on Firebase Hosting. Does anyone have advice on how to restrict installation only to devices and block desktop browsers from accessing the app? My main goal is ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

What is the process for transforming this information into JSON format with Javascript?

I have a server response with data that needs to be converted to JSON using JavaScript. country=Philippines\r\n countryid=840\r\n operator=Globe Telecom Philippines\r\n operatorid=246\r\n connection_status=100\ ...

Is it possible to send arguments to the functions executed by "jQuery then"?

Check out the complete code here: http://jsfiddle.net/BurFz/ http://jsbin.com/dagequha/1/edit?js,console /** * executed function chain */ func1('arg1').then(func2).then(func3).then(function () { console.log('execution comp ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

When the input tag is set to null, the array that holds e.target.files will be devoid of any content

Hey there, I'm currently in the process of uploading a folder. However, I encountered an issue when trying to upload the same folder again. It seems that the data was empty when I attempted to set it to null. const uploadFolders = []; let uploadFolder ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Analyzing information in JavaScript using Selenium

Currently, I am facing an issue while trying to extract data from a JSON file using JavaScript. I am able to successfully read data from the file, but when I try to pass this data within my code, it results in errors. Any guidance or assistance on this mat ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

Ways to revert to the initial state in React.js

Check out my codeSandbox project here: https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js I'm having trouble getting the items back to their original presentation when clicking on "default" - sorting by price wor ...

A guide on verifying the username, password, and chosen role from a database through the use of javascript/ajax or alternative validation methods

If the user's name, password, or role is incorrect, I want to display an error message using validations like AJAX/JavaScript. index.php <html> <head> </head> <body> <style> body { wi ...

How can constants in AngularJS be defined in relation to other constants?

I've been attempting to set constants using other constants, but it seems that this cannot be achieved due to the initial constant not being ready when the dependent constant requires it. I am curious to know if this is indeed an impossible task. My ...

Utilizing JavaScript to dynamically adjust the height of one div to match the height of another div

Struggling to adjust the height of one div to match another using the following code: var aboutheight=document.getElementById('about').offsetHeight; document.getElementById('sampledogs').setAttribute("style","height:aboutheight"); Des ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

How to select a DOM element in Angular 2.x

Although it may seem simple, there are not many examples of using Angular 2.0 yet. In one of my components, I have a situation where I need to add a class to the body tag. However, my application is bootstrapped deeper than the body element, so I am looki ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...