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 OverflowThis 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!
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.
Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery - Stack Overflow
Regex allow digits and a single dot - Stack Overflow
regex - Javascript function need allow numbers, dot and comma - Stack Overflow
javascript match Regex for numbers and only dot character - Stack Overflow
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 '.'
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;
}
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
try this one,
^[0-9]*(\.|,)?[0-9]*$
this take below cases:
1111, .0000 123,12 12.12 12345
but if you want only
111,11 11.11 12345
so please use this
^[0-9]+(\.|,)?[0-9]+$
to force use dot/comma please use this
^[0-9]+(\.|,)[0-9]+$
add this code
$("#testId").keyup(function(){
var vals = $("#testId").val();
if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
$("#testId").val(vals);
else
vals = vals.replace(/.
("#testId").val(vals);
});
and change input type to
type="text"
If you want to allow 1 and 1.2:
(?<=^| )\d+(\.\d+)?(?=$| )
If you want to allow 1, 1.2 and .1:
(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )
If you want to only allow 1.2 (only floats):
(?<=^| )\d+\.\d+(?=$| )
\d allows digits (while \D allows anything but digits).
(?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.
Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.
\d*\.\d*
Explanation:
\d* - any number of digits
\. - a dot
\d* - more digits.
This will match 123.456, .123, 123., but not 123
If you want the dot to be optional, in most languages (don't know about jquery) you can use
\d*\.?\d*
Firstly your regex currently doesn't allow comma, which is your requirement.
Secondly, you haven't used any quantifier, so your regex will match only a single character - one of [0-9] or a dot. You need to use a quantifier.
Thirdly, instead of using pipe, you can move all characters inside the character class only.
Try using the below regex:
/^[0-9.,]+$/
Quantifier + is used to match 1 or more occurrence of the pattern.
^ and $ anchors match the beginning, and end of the string respectively.
No need for JavaScript:
<input type="text" pattern="[0-9.,]+" title="Please enter a valid decimal number." />
Modern browsers will handle this perfectly.
If you want to specifically allow commas as thousand separators and a single decimal point, try this:
... pattern="\d{1,2}(,\d{3})*(\.\d+)?" ...
Note that I am firmly against blocking user input. They should be able to type what they want, and then told if they enter something invalid.
In case you dont mind accepting just a point, this should do it
\d*\.\d*
Otherwise, the more complete answer could look like this:
\d*\.\d+)|(\d+\.\d*)
You can use the following regex to select your integer and fractional parts than add 1 to your integer part depending to your fractional part:
Regex: ^(\d+)\.(\d+)$
In use:
function roundOff(str) {
return str.replace(/^(\d+)\.(\d+)$/g, ($0, $1, $2) => $2.split('')[0] >= 5 ? parseInt($1) + 1 : parseInt($2));
}
var str1 = roundOff('123.123')
console.log(str1); // 123
var str2 = roundOff('123.567')
console.log(str2); // 124
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.
if you just want to handle number ,you can try this:
valueTest.match(/^-?\d+(\.\d+)?$/)