Home > Enterprise >  Regex to validate both text & numbers are failing?
Regex to validate both text & numbers are failing?

Time:05-19

I have 2 textboxes:

  • 1 Textbox that can contain "integers or a period"
  • 1 Textbox that can contain "only integers"

TEXTBOX ONE contains the text "10.10,12,139" & should FAIL the RegEx
TEXTBOX TWO contains the text "1004" & should PASS the RegEx

I am trying to validate them using RexEx...and both are failing?

Q: What am I doing wrong here?

CODE EXAMPLE TEXTBOX ONE:
The expectation in this case is...

  • The TEXTBOX_VALUE test should return false
  • The STRING_VALUE test should return true

Both return false...why?

// Textbox contains "10.10,12,139"...yet BOTH return false? Why?
const regex = new RegExp("^([0-9\.])$");

let test_TEXTBOX_VALUE = regex.test(input.val().trim());
let test_STRING_VALUE = regex.test("10.10.12.139");

CODE EXAMPLE TEXTBOX TWO:
The expectation in this case is...

  • The TEXTBOX_VALUE test should return false
  • The STRING_VALUE test should return true

Both return false...why?

// Textbox contains "4001"...yet BOTH return false? Why?
const regex = new RegExp('^\d $');

let test_TEXTBOX_VALUE = regex.test(input.val().trim());
let test_STRING_VALUE = regex.test("4001");

CodePudding user response:

First example is wrong because it's missing the plus. i.e.

const regex = new RegExp("^([0-9\.])$");

Should be:

const regex = new RegExp("^([0-9\.] )$");

otherwise it'll only match 1 character strings

Or equally:

const regex = new RegExp("^([0-9\.] )$");

because the escaping on . in a [] is redundant.

The second is probably falling foul of escaping so you need to double-escape. i.e.

const regex = new RegExp('^\d $');

Should be:

const regex = new RegExp('^\\d $');

CodePudding user response:

I agree with @Richard Wheeldon, but this is a much simpler answer: /^\d $/.test() This catches all positive integer values.

For negatives use: /^(?:-?[1-9]\d*$)|(?:^0)$/.test()

Examples:

console.log(/^(?:-?[1-9]\d*$)|(?:^0)$/.test("10")) //returns true
console.log(/^(?:-?[1-9]\d*$)|(?:^0)$/.test("-10")) //returns true
console.log(/^(?:-?[1-9]\d*$)|(?:^0)$/.test("10.5")) //returns false

console.log(/^\d $/.test("10")) //returns true
console.log(/^\d $/.test("-10")) //returns false
console.log(/^\d $/.test("10.5")) //returns false

  • Related