Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow only a single dot in a textbox

I have one text input.

I wrote a regex for masking all special characters except . and -. Now if by mistake the user enters two . (dots) in input, then with the current regex

var valueTest='225..36'

valueTest.match(/[^-.\d]/)

I expected that the number will not pass this condition

How to handle this case. I just want one . (dot) in input field since it is a number.

like image 896
Arjun Prajapati Avatar asked Jul 31 '14 07:07

Arjun Prajapati


People also ask

How to allow only one dot in textbox JavaScript?

function allowOneDot(txt) { if ((txt. value. split("."). length) > 1) { //here, It will return false; if the user type another "." } }

How do you escape a dot in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.

What is U flag in regex?

Flag u enables the support of Unicode in regular expressions. That means two things: Characters of 4 bytes are handled correctly: as a single character, not two 2-byte characters. Unicode properties can be used in the search: \p{…} .


1 Answers

I think you mean this,

^-?\d+(?:\.\d+)?$

DEMO

It allows positive and negative numbers with or without decimal points.

EXplanation:

  • ^ Asserts that we are at the start.
  • -? Optional - symbol.
  • \d+ Matches one or more numbers.
  • (?: start of non-capturing group.
  • \. Matches a literal dot.
  • \d+ Matches one or more numbers.
  • ? Makes the whole non-capturing group as optional.
  • $ Asserts that we are at the end.
like image 148
Avinash Raj Avatar answered Oct 13 '22 00:10

Avinash Raj