This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

  • http://www.regular-expressions.info/javascript.html

You can also test the above regex here:

  • http://www.regular-expressions.info/javascriptexample.html

Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!

Answer from jahroy on Stack Overflow
Top answer
1 of 16
75

This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

  • http://www.regular-expressions.info/javascript.html

You can also test the above regex here:

  • http://www.regular-expressions.info/javascriptexample.html

Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!

2 of 16
25

Use Jquery instead. Add a decimal class to your textbox:

<input type="text" class="decimal" value="" />

Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.

$('.decimal').keyup(function(){
    var val = $(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    $(this).val(val); 
});​

Check this fiddle: http://jsfiddle.net/2YW8g/

Hope it helps.

Discussions

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery - Stack Overflow
I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format. This should occure .on("input") meaning as the user types it sho... More on stackoverflow.com
🌐 stackoverflow.com
Regex allow digits and a single dot - Stack Overflow
What would be the regex to allow digits and a dot? Regarding this \D only allows digits, but it doesn't allow a dot, I need it to allow digits and one dot this is refer as a float value I need to be More on stackoverflow.com
🌐 stackoverflow.com
regex - Javascript function need allow numbers, dot and comma - Stack Overflow
Is there a way to limit only one dot or one comma? In your regex, 12.34,45 is correct 2016-07-04T14:10:51.417Z+00:00 ... Modern browsers will handle this perfectly. If you want to specifically allow commas as thousand separators and a single decimal point, try this: More on stackoverflow.com
🌐 stackoverflow.com
javascript match Regex for numbers and only dot character - Stack Overflow
I need to match Regex for an input text. It should allow only numbers and only one dot. Below is my pattren. (?!\s)[0-9\.\1]{0,} This is allowing only numbers and allowing multiple dots. How to w... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 5
4

Everytime your event handler runs, the input grows by one character, so I think a better approach would be to check if the input still matches your regex rule and, if not, restore the previous value and force it to blur().

Try to update your event handler like this and it should work:

let curValue = '';
function onlyNumberAndADot(event) {
  const valid = /^\d*\.?(?:\d{1,2})?$/;
  const text = event.target.textContent;  
  if (!valid.test(text)) {
    event.target.textContent = curValue;
    event.target.blur();
  } else {
    curValue = event.target.textContent;
  }
}

document.getElementById("test1").addEventListener("input", function(event) {
  onlyNumberAndADot(event);
});

document.getElementById("test1").addEventListener("blur", function(event) {
  event.target.textContent = event.target.textContent.replace(/\.$/,'');
});

I created a fiddle with this solution and it works.

Notice that you have to temporarily allow inputs like '0.', otherwise users won't be able to type in the dot, so I did another verification on blur event, to remove the final '.'

2 of 5
3

This should cover all your cases.

/^(?:\d+(?:\.\d{1,2})?|\.\d{1,2})$/

Readable version

 ^ 
 (?:
      \d+ 
      (?: \. \d{1,2} )?
   |  \. \d{1,2} 
 )
 $

update after chat.

Seems the regex needs to operate on input in real time event handler,
like keypress paste etc..

To do that, it needs to be a progressive optional type of regex
to allow for partial matching, yet strip off invalid text.

That regex is
Find /^(\d+(?:\.\d{0,2})?|\.\d{0,2})?.*?$/
Replace "$1"

Readable version

 ^ 
 (                             # (1 start)
      \d+ 
      (?:
           \. 
           \d{0,2} 
      )?
   |  \. \d{0,2} 
 )?                            # (1 end)
 .*? 
 $

When submitting the current entry a final validation regex could
be necessary, but maybe not.

That regex is something like this ^(?:\d+(?:\.\d{0,2})?|\.\d{1,2})$

The only possible invalidation will only ever be a single dot, or a blank
which was a valid current input but not valid in the final.

If it doesn't match, just set the input to 0 and go from there.


update

To limit rewriting the input text on every event, add a couple
of extra filter steps in the handler.

var RxFinalForm = /^(?:\d+(?:\.\d{0,2})?|\.\d{1,2})$/;
var RxRmvInvalid = /[^\d.]+/g;
var RxPartialForm = /^(\d+(?:\.\d{0,2})?|\.\d{0,2})?.*?$/;

function onlyNumber(element) { 
 ob = element.target; 
 var sContent = ob.textContent;

 // Test if the current content is a valid Final Form.
 // Note the ob.textContent does not need to be changed,
 // thus preserving the caret position.
 // -----------------------------------------------------
 if ( RxFinalForm.test( sContent ) )
    return;  // No need to change anything, just return

 // Remove any invalid characters ( non - dot/digit )
 // --------------------------------------------------
 sContent = sContent.replace( RxRmvInvalid, "" );

 // Extract the Partial Form
 // -------------------------
 sContent = sContent.replace( RxPartialForm, "$1");

 // Finally, if 'ob.textContent' does not equal 'sContent', change it.
 // This will happens when an extra dot was enterred.
 // ------------------------------------------------------------------
 if ( ob.textContent !== sContent )
    ob.textContent = sContent;
} 
🌐
Infinitbility
infinitbility.github.io › posts › how to allow only numbers and dot in javascript using regex?
how to allow only numbers and dot in javascript using regex? | Infinitbility
September 14, 2022 - To allow only numbers and dot, use this regex /^[0-9]*\.?[0-9]*$/ it will return true if value contain only numbers and dots. Let’s see short example of javascript regex allow numbers and decimals only.
🌐
Nzstarch
nzstarch.co.nz › 2o1w0y › 4a935c-regex-to-allow-only-numbers-and-single-dot-in-javascript
regex to allow only numbers and single dot in javascript
By default, period/dot character only matches a single character. How to keep only letters and numbers in String? In addition to the standard notation, \p{L}, Java, Perl, PCRE, the JGsoft engine, and XRegExp 3 allow you to use the shorthand \pL. There are other special characters as well, that have special meaning in a regexp. To match any character in JavaScript, including line breaks, use a construct such as [\D\d]. re: in the textbox accept numbers and only one dot Use this javaScript function function num(e) { var k; document.all k = e.keyCode : k = e.whic.
Find elsewhere
🌐
Et-foundation
set.et-foundation.co.uk › digital-assets › self-assessment › bczmnlk › fly-fishing-tackle-buying-guides › regex-to-allow-only-numbers-and-single-dot-in-javascript-4dfdb8
regex to allow only numbers and single dot in javascript
A line that doesn ’ t contain a word given regular expression Library a! More digits \d.To mark how many we need, we should use character classes, e.g were allowed. Character valid and add to the input regex to allow only numbers and single dot in javascript not \D\d ] this article, we are going …
🌐
Axcelerate
enrolments-wilsonmedicone.axcelerate.com.au › wp-content › unfinished-wood-qncu › regex-to-allow-only-numbers-and-single-dot-in-javascript-e249f3
regex to allow only numbers and single dot in javascript
It will find only second line: ... (just like in regular strings). Maximum three decimal places are not required. JavaScript JavaScript does not support single-line mode....
🌐
Sololearn
sololearn.com › en › Discuss › 3102479 › regex-only-allow-numbers-one-dot-on-input
Regex only allow numbers & one dot on Input | Sololearn: Learn to code for FREE!
I am a beginner in javascript and regex. But I'll keep trying. Args in your code return true or false. I’m thinking I need to use event.preventDefault() for all false then? To prevent to put someting else than numbers and more than one dot in my input or am I thinking completely wrong?
🌐
C# Corner
c-sharpcorner.com › blogs › allow-only-numeric-values-and-allow-only-one-dot-in-textbox-using-javascript1
Allow Only Numeric Values and allow Only one DOT in TEXTBOX using JavaScript
May 21, 2020 - In this article, we will see how to Allow only Numeric value and Only one DOT in Textbox. This example will helpful when we want to use the PRICE field in the textbox.
🌐
Sololearn
sololearn.com › en › Discuss › 3102479 › regex-only-allow-numbers-one-dot-on-input-
Regex only allow numbers & one dot on Input
sl_scroll_/en/Discuss/1074366/challenge-find-lowest-number-with-devisor-225-and-digits-only-0-and-1-beginners-welcome-just-read-threadPending
🌐
Stack Overflow
stackoverflow.com › questions › 59193083 › allow-input-to-add-only-numbers-comma-or-dot-with-regex
Allow input to add only numbers comma OR dot with regex - Stack Overflow
December 5, 2019 - Guessing you want to match only digits and one dot or comma you could start with something like ^\d*[.,]?\d*$ Please provide better context and code to your question! ... Doesn't your regex mean ignore all the characters you specified?
🌐
The Web Dev
thewebdev.info › home › how to check for strings with only numbers and dot with javascript?
How to check for strings with only numbers and dot with JavaScript? - The Web Dev
January 16, 2022 - To check for strings with only numbers and dot with JavaScript, we can call the JavaScript string match method to return matches of the pattern. How to Check for Canadian Postal Code Strings with JavaScript?
🌐
CodingForum
codingforum.net › home › client side development › javascript programming
Regex allow only backspace, numbers, dot and comma - CodingForum
January 18, 2016 - $('#quantity').bind('keydown keypress keyup', on); function on(evt) { var theEvent = evt || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode( key ); var regex = /^[0-9\b.,]+$/; if( !regex.test(key) ) { theEvent.returnValue = false; if(theEvent.preventDefault) ...