Home > Mobile >  i want to restrict multiple negative symbols in numeric using regex in typescript. im getting error
i want to restrict multiple negative symbols in numeric using regex in typescript. im getting error

Time:01-03

How to restrict multiple negative sign in the textbox. below code is not allowing my to type even single negative symbol.

my regex code -

public AmountFormat ="^(\\ ?\\-? *[0-9] )([,0-9]*)([0-9])*$";

error -

not allowing to enter (-) symbol if i write regex in the variable.

public AmountFormat ="((^|, )(-|-?[0-9]\d*(\.\d )?)) $"; //not working

 return /((^|, )(-|-?[0-9]\d*(\.\d )?)) $/.test(input);//working

CodePudding user response:

try

public AmountFormat =/^-?\d*(\d\.\d*)?$/;

details:

const isValid = (input) => {
  const AmountFormat = /^-?\d*(\d\.\d*)?$/;
  return AmountFormat.test(input);
}


console.warn(isValid('100'));

// true


console.warn(isValid('-100.0'));

// true


console.warn(isValid('--100'));

// false

console.warn(isValid('-'));

// true

CodePudding user response:

The problem is that with [0-9] you require a digit in valid input, so there is no way to start with just -.

I would not allow spaces after the sign -- this is not standard.

You could use /^-?\d*(\d\.\d*)?$/. If the comma is intended as decimal separator, then replace that \. with just ,.

Here is a runnable snippet:

const regex = /^-?\d*(\d\.\d*)?$/

let input = document.querySelector("input");
input.addEventListener("input", validate);

let previous = input.value;

function validate() {
    if (!regex.test(input.value)) {
        input.value = previous;
    } else {
        previous = input.value;
    }
}
<input>

  • Related