Home > Blockchain >  JavaScript regex inline validation for basic calculation string with one operator
JavaScript regex inline validation for basic calculation string with one operator

Time:09-16

I've written a basic 2 operand calculator app ( - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed. An example looks like:

//check if operator is present
       if(/[ \-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
            if(!/^\d \.?\d*[ \-*\/]?\d*\.?\d*$/.test(display1.textContent)){
                console.log('invalid')
                return false
            }
//validate the string character by character before operator
        } else {
            if(!/^\d \.?\d*$/.test(display1.textContent)){
                console.log('invalid')
                return false
            } 
        }

In the above, a valid character doesn't return false:

23.4x0.00025 (no false returned and hence the string is typed out)

But, if an invalid character is typed the function returns false and the input is filtered away:

23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)

23.4x0. is typed

It works pretty well but allows for the following which I would like to deal with: 2. .1
I would prefer 2.0 0.1

My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [ -*/] then the next character must be a number, else the next char can be any char (while following the overall logic).

The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.

if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.

Any suggestions about this specific problem would be really helpful.

Thanks

https://github.com/jdineley/Project-calculator

CodePudding user response:

For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)

Demo:

const validate = s => /^(\d (\.\d*)?((?<=\d)[ */-]|$))*$/.test(s);

document.querySelector("input").addEventListener("input", function () {
    this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
    
Input: <input>

CodePudding user response:

Thanks @trincot for the tips using capturing groups and look around. This helped me write what I needed:

https://regex101.com/r/khUd8H/1

git hub app is updated and works as desired. Now just need to make it pretty!

  • Related