0

var regex = /^(?=.*[_$@])(?=.*[^_$@.])[\w$@]$/;
var text = "12a/d";
console.log(regex.test(text))

it's not working. I want it's allow input only number and float ex: '12.2,2' , '12', '12.2', '2,2'

Thank everyone

Henry
  • 13
  • 3
  • `[\w$@]` only matches one char. Do you want to match one or more ? `[\w$@]+`? But `[\w$@]` does not allow `/`. Try `/^(?=.*[_$@])(?=*[^_$@.])[\w$@\/]+$/` – Wiktor Stribiżew Nov 10 '22 at 09:18
  • there are pure javascript ways as well, [check this](https://stackoverflow.com/a/3885844/5953610) – Mechanic Nov 10 '22 at 09:35
  • To check if a string is a JS-parsable float, use the test : `+n !== (+n|0)` – Mathieu CAROFF Nov 10 '22 at 09:38
  • Depending on your use case, you might need a different regex (e.g. if you want to parse a JSON float), but here's a regex which checks that a string is a float: `^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$`. It comes from https://stackoverflow.com/q/12643009/regular-expression-for-floating-point-numbers – Mathieu CAROFF Nov 10 '22 at 09:41
  • Maybe you want `/^(?:\d*[,.])*\d+$/`? See https://regex101.com/r/3sAIII/1 – Wiktor Stribiżew Nov 10 '22 at 10:10

1 Answers1

0

I am not clear about your number format examples. Is 12.2,2 two numbers separated by comma? Is 2,2 the German locale representation of a floating number?

Here is a number validation for the English locale with valid and invalid numbers as input:

const input = [
  '0',
  '1',
  '1.',
  '1.2',
  '-1.2',
  '+1.2',
  '.123',
  '123.45',
  '1,123.45',
  '123,123.45',
  '1,123,123.45',
  '', // invalid
  '1-2', // invalid
  '1+', // invalid
  '1x', // invalid
  '1,12.9', // invalid
  '1,1234.9', // invalid
];
const re = /^[+-]?((\d+|\d{1,3}(,\d{3})+)(\.\d*)?|\.\d+)$/
input.forEach(str => {
  console.log( str + ' => ' + re.test(str));
});

Output:

0 => true
1 => true
1. => true
1.2 => true
-1.2 => true
+1.2 => true
.123 => true
123.45 => true
1,123.45 => true
123,123.45 => true
1,123,123.45 => true
 => false
1-2 => false
1+ => false
1x => false
1,12.9 => false
1,1234.9 => false

Explanation of regex:

  • ^ -- anchor at beginning of string
  • [+-]? -- optional + or -
  • ( -- group 1 start
    • ( -- group 2 start
      • \d+ -- 1+ digits
    • | -- logical OR in group 2
      • \d{1,3}(,\d{3})+ -- 1 to 3 digits, followed by 1+ sets of comma and 3 digits
    • ) -- group 2 end
    • (\.\d*)? -- optional dot and 0+ digits
  • | -- logical OR in group 1
    • \.\d+ -- a dot an 1+ digits
  • ) -- group 1 end
  • $ -- anchor at end of string
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20