0

I want to validate the user input,

it should accept,

1+2
1.2+56+3.5

it should not accept any alphabets, special characters other than . and +

and mainly it should not accept ++ and ..

please help me with regular expression.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Dosti
  • 161
  • 4
  • 17

3 Answers3

0

Something like this should suffice

^([+]?\d+(\.\d+)?)*$

http://regex101.com/r/qE2kW1/2

Source: Validate mathematical expressions using regular expression?

Community
  • 1
  • 1
ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
0

This should work:

var regex = /^[0-9]+(\.[0-9]+)?(\+[0-9]+(\.[0-9]+)?)*$/;
"1+2".match(regex); // not null
"1.2+56+3.5".match(regex); // not null
"1++2".match(regex); // null
"1..2".match(regex); // null

online: http://regex101.com/r/zJ6tP7/1

codebox
  • 19,927
  • 9
  • 63
  • 81
  • This is what i have http://jsfiddle.net/DwKZh/763/ , I tried all expression provided here but still allowing me to enter invalid inputs. – Dosti Oct 31 '14 at 06:21
  • please give an example of an invalid input that the satisfies the regex – codebox Oct 31 '14 at 08:10
  • none of those strings match the regex - try them out on the regex101 page I linked to or just in the JS console in your browser: "1++2".match(REGEX HERE) – codebox Oct 31 '14 at 08:19
  • added more example above, also please distribute some upvotes and accept an answer so that people will be more likely to help you in the future – codebox Oct 31 '14 at 08:31
0

Note that I'm assuming it should not accept .+ or +. as well. I'm not assuming that you require checking for multiple decimals prior to an addition, meaning this will accept 3.4.5 I'm also assuming you want it to start and end with numbers, so .5 and 4+ will fail.

(\d*[\.\+])*(\d)*

This takes any amount of number values, followed by a . or a +, any number of times, followed by any other number value.

To avoid things like 3.4.5 you'll likely need to use some sort of lookaround.

EDIT: Forgot to format regular expression.