15

How to validate such number input with one RegEx. Strings are not allowed. Two decimal positions after dot or comma.

Example:

123.34
1.22
3,40
134,12
123

stema
  • 90,351
  • 20
  • 107
  • 135
thesis
  • 2,565
  • 5
  • 26
  • 37
  • 1
    possible duplicate of [Decimal or numeric values in regular expression validation](http://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation) – JJJ Oct 25 '11 at 08:30

6 Answers6

26

Try this regex:

/^(\d+(?:[\.\,]\d{2})?)$/

If $1 exactly matches your input string then assume that it is validated.

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
9

Try This,

/^(\d+(?:[\.\,]\d{1,2})?)$/
Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
2

This is my method to test decimals with , or . With two decimal positions after dot or comma.

  1. (\d+) : one or more digits
  2. (,\d{1,2}|\.\d{1,2})? : use of . or , followed by 2 decimals maximum

const regex = /^(\d+)(,\d{1,2}|\.\d{1,2})?$/;

console.log("0.55 returns " + regex.test('0.55')); //true
console.log("5 returns " + regex.test('5')); //true
console.log("10.5 returns " + regex.test('10.5')); //true
console.log("5425210,50 returns " + regex.test('5425210,50')); //true

console.log("");

console.log("10.555 returns " + regex.test('10.555')); //false
console.log("10, returns " + regex.test('10,')); //false
console.log("10. returns " + regex.test('10.')); //false
console.log("10,5.5 returns " + regex.test('10,5.5')); //false
console.log("10.5.5 returns " + regex.test('10.5.5')); //false
Melchia
  • 22,578
  • 22
  • 103
  • 117
2
pat = re.compile('^\d+([\.,]\d\d)?$')
re.match(pat, '1212')
<_sre.SRE_Match object at 0x91014a0>
re.match(pat, '1212,1231')
None
re.match(pat, '1212,12')
<_sre.SRE_Match object at 0x91015a0>
spicavigo
  • 4,116
  • 22
  • 28
0
Private Sub TexBox_TextChanged(sender As Object, e As EventArgs) Handles TexBox.TextChanged

    TexBox.Text = System.Text.RegularExpressions.Regex.Replace(TexBox.Text, "[^\d\.]", "")

    TexBox.Select(TexBox.Text.Length + 1, 1)

    Dim x As Integer = 0

    For Each c In TexBox.Text
        If c = "." Then
            x += 1

            If (x > 1) Then
                TexBox.Text = TexBox.Text.Substring(0, TexBox.Text.Length - 1)
                TexBox.Select(TexBox.Text.Length + 1, 1)
            End If


        End If
    Next

End Sub
MJT7
  • 23
  • 2
0

A more precise validation over thousands separator and prefix signal:

const re = /^[-\\+]?\s*((\d{1,3}(,\d{3})*)|\d+)(\.\d{2})?$/
console.log(re.test('-1000000.00')) // true
console.log(re.test('-1,000,000.00')) // true
console.log(re.test('-1000,000.00')) // false
dgolive
  • 425
  • 3
  • 8