Accept only numeric values that are either exactly 6 digits long or exactly 8 digits long with 2 decimal places

After developing a validator to ensure that a digit is a number and restricts it to having 2 digits after the decimal place, I realized that it does not account for two specific scenarios: a 6-digit number with no decimal places (e.g. 123456) or an 8-digit number with 2 decimal places (e.g. 123456.78). Below is the code that addresses this concern:

function validateInt2Dec(value, min, max) {

    if (Math.sign(value) === -1) {
        var negativeValue = true;
        value = -value
    }

    if (!value) {
        return true;
    }
    var format = /^\d+\.?\d{0,2}$/.test(value);
    if (format) {
        if (value < min || value > max) {
            format = false;
        }
    }
    return format;
}

This function can be implemented in a formly form as shown below:

     vm.fields = [
             {
                className: 'row',
                fieldGroup: [
                    {
                        className: 'col-xs-6',
                        key: 'payment',
                        type: 'input',
                        templateOptions: {
                            label: 'Payment',
                            required: false,
                            maxlength: 8
                        },
                        validators: {
                            cost: function(viewValue, modelValue, scope) {
                                var value = modelValue || viewValue;
                                return validateInt2Dec(value);
                            }
                        }
                    }
                ]
            }
        ];

To accommodate the aforementioned scenarios, additional conditions need to be added to the validator function.

Answer №1

Here is a regular expression that you can try out:

var regex = /^\d{1,6}(\.\d{1,2})?$/;

console.log(regex.test("123456"));
console.log(regex.test("123456.78"));
console.log(regex.test("123456.00"));
console.log(regex.test("12345.00"));
console.log(regex.test("12345.0"));
console.log(regex.test("12345.6"));
console.log(regex.test("12.34"));
console.log(regex.test("123456.789"));

Answer №2

Testing the waters with regex101 indicates that it meets your criteria.

Solution: ^(\d{6})?(\d{8}\.\d{2})?$

  • Group 1 ^(\d{6})?- either 6 digits

  • Group 2 ^(\d{6})?(\d{8}\.\d{2})?$ - or 8 digits with 2 decimal places

Answer №3

To avoid increasing regex complexity, you have the option of adding a check for maxLength before proceeding with the validation process.

var str = value.toFixed(2);
var maxLength = (str.indexOf(".") > -1 ? 8 : 6);
if (str.length > maxLength) {
    return; //input is considered invalid
}

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

Using Three.js to Project Objects onto a Plane that is Perpendicular to the Camera Orientation

I have a basic setup in Three.js involving some planes. Currently, when clicked, the planes move to random positions. Instead of the random movement, I want the planes to transition into a new grid that is perpendicular to the camera, aligning the project ...

Leveraging the power of Promise creation

I am facing an issue where I am trying to utilize the getPromise function with various URLs in order to obtain different promises, but encountering undefined values in the success function of the second promise. var http=require('http'); var URL ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Spin the div in the opposite direction after being clicked for the second time

After successfully using CSS and Javascript to rotate a div by 45 degrees upon clicking, I encountered an issue when trying to rotate it back to 0 degrees with a second click. Despite my searches for a solution, the div remains unresponsive. Any suggestion ...

Explore creating a dial number using React

Hey there, I'm currently working on developing a component. Just to clarify, I am not using react-native for this project. Instead, I would like to utilize React to scroll a number similar to how an image scrolls. https://i.sstatic.net/c1Tu8.png Th ...

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

What is the process of including metadata in stripe when completing a purchase?

const mergeData = function (prod, pot, data) { const newData = [...prod, ...pot]; const finalCheckout = []; for (let i = 0; i < newData.length; i++) { finalCheckout.push({ name: newData[i].plantName || newData[i].potName, images: [newData[i].images ...

Enhance Your Jekyll Site with the Minimal Mistakes Theme Plugin

Hi there! I'm relatively new to website programming and could really use some assistance. I've been attempting to integrate the jekyll-lunr-js-search (https://github.com/slashdotdash/jekyll-lunr-js-search) into the minimal-mistakes theme, but I&a ...

Initial input firing empty string on React's onChange event

Issue - When I input text for the first time, no string output is displayed. As a result, the last character of the input is not showing up. What could be causing this? Specific focus - Concentrating on the name property const [options, setOptions] = useS ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

What is the best way to ensure that the larger child divs always fit perfectly within the parent div?

Creating a Responsive Layout <div class="container"> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> </div> CSS Styling .box1, .box2, .box3{ display: block; f ...

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

three.js fur effect not appearing on screen

I have been working on understanding and implementing fur in three.js. I came across an example at which I used as a reference to comprehend the code. The model loads successfully, but the issue arises when the fur texture doesn't load. I have check ...

"Experience random updates in the priv/static/js/app.js file whenever changes are made to Vue files in the Phoenix/Elixir/V

I have a vue.js/Phoenix application and I am currently facing a challenge with configuring the frontend assets properly. I have noticed that my priv/static/js/app.js file keeps updating whenever I make changes in other files, and I am unable to understand ...

How does Mongoose handle returning objects internally?

I have a story that might be a bit tedious, but I was really puzzled by this issue. Here's the scenario: I was attempting to modify the value of the article object returned by the Mongoose static Model method in my service layer. This is what the ob ...

Sending complete form details to a service using Angular

Is there a way to post all form fields without having to individually specify each one? I have a form with numerous fields and I would like to send the entire form object in one go using a post method. However, when I attempt to do this by posting the $sco ...