1

I'm looking for a regular expression for accepting only numbers and number with , or . characters. For example

12345--accepted
1.2344 accepted
1,2345 accepted
+123.34@@##sdsd--not accepted

I'm using this /^\d+$/ fot it does not allow , or . seperators

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
RamAlx
  • 6,976
  • 23
  • 58
  • 106

1 Answers1

1

You can use this regex ^\d+([.,]\d+)?$:

regex demo

var array = ["12345", "1.2344", "1,2345", "+123.34@@##sdsd"];
for (var i = 0; i < array.length; i++) {
    let regex = /^\d+([.,]\d+)?$/g; 
    var patt = new RegExp(regex);
    console.log(patt.test(array[i]))
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • hi, can you take look at my question? https://stackoverflow.com/questions/44726427/replace-apostrophe-in-the-middle-of-the-word-with-in-java – vaibhavcool20 Jun 23 '17 at 17:04
  • const regPrc = /^\d+([.,]\d+)?$; this is returning me an error that the regular is unterminated – RamAlx Jun 23 '17 at 17:06
  • Guys i'm doing something terribly wrong. I'm writing: const reqPrice = /^\d+([.,]\d+)?$/g; and then if (!reqPrice.test(price)) { errors.price = 'Price can contain only numbers!!!'; } and it does not triggered. What am i doing wrong? – RamAlx Jun 23 '17 at 17:26
  • @user7334203 i'm not so familiar with javascript can you try this `const reqPrice = /^\d+([.,]\d+)?$/g; if (reqPrice.test('12345')) { console.log('Correct'); } else{ console.log('Not correct'); }` i think you miss the else statement – Youcef LAIDANI Jun 23 '17 at 17:31
  • @YCF_L Ah ok, I won't tell anyone. – vaibhavcool20 Jun 23 '17 at 17:32