Match only numbers including decimals [duplicate] - javascript

This question already has answers here:
Decimal or numeric values in regular expression validation
(13 answers)
Closed 2 years ago.
I have an input field I want the input value to be only numbers and decimals nothing more but the problem is that when I type the Unicode characters and letters and semicolons the input value excepts it how do I achieve that.
let newValue = item.value.replace(new RegExp(/[a-z] && [#!#$%^&*()_+}{}|:,=] /,'ig'), "");
item.value = newValue;

If you want to only accept number and decimals for your input you can do either of these two ways:
Use input type number.
<input type="number"/>
Use a regex like below, which accept only numbers and decimals:
^-?[0-9]\d*(\.\d+)?$
NOTE: If you want to use the comma (and . in any place) as input also, you can use this one (according to this post):
^-?[0-9][\.\d]*(,\d+)?$

Update
Validation on input:
var org = '';
document.getElementsByTagName('input')[0].oninput = function(e) {
var val = document.getElementsByTagName('input')[0].value;
if(val == '' || val.match(/^([0-9]*\.)?[0-9]*$/)) {
org = val;
} else {
val = org;
}
document.getElementsByTagName('input')[0].value = val;
}
document.getElementsByTagName('input')[0].oninput();
Number here: <input value="1.23" type="text" /><br />

function scrubInput() {
let numberInputElem = document.getElementById('numberInput');
const regex = /[^0-9\.]/
let newValue = numberInputElem.value.replace(regex, "");
numberInputElem.value = newValue;
}
<input type="text" id="numberInput" oninput="scrubInput()"/>

Related

How to remove the leading zeros in the number inside input type='number'? [duplicate]

This question already has answers here:
Remove/ truncate leading zeros by javascript/jquery
(17 answers)
Closed 19 days ago.
I am a beginner in React JS. I have a use case in that I want to correct the number that a user enters in <input type='number> field.
By default, a user can enter numbers with leading zeros like 0002 or -0042, etc.
I want to make it such that the leading zeros are removed when the user enters the number. Also, the user should be able to enter decimal as well as negative numbers. I have done it using onBlur but I want to somehow do it onChange method itself.
onChange=()=>{ ... }
<input type = 'number' onChange={onChange}>
I want to make it such that the leading zeros are removed when the user enters the number.
You can remove the leading zeros with String.replace:
// ... code that obtains the user input in `inputText` ...
inputSanitisedText = inputText.replace(/^0+/, '')
(I am assuming you don't want to change the user's input while they're entering it. That would be very bad UI design.)
You can use regex to remove zeros from beginning: /^0+/
In your case:
onChange = (e) => {
const _removedZeros = e.target.value.replace(/^0+/, '')
///...
}
you can simply multiplied value to 1, like this :
const [value, setValue] = useState("");
<input
value={Boolean(value) ? value : ''}
type="number"
onChange={(e) => setValue(e.target.value * 1)}
/>
in this way user cannot type leading zeros
As per your description, you can solve this by using the parseFloat() function. This function will remove the leading zeros and will convert the input value to a decimal/fractional number.
The code should be like this:
const onChange = (event) => {
const value = parseFloat(event.target.value);
event.target.value = isNaN(value) ? '' : value;
};
something like this?
foo.oninput = (e) => {
const value = foo.value;
let [_, sign, integer, decimals] = value.replace(/[^\d\.\-]/g, "") // invalid characters
.replace(/(\..*?)\./g, "$1") // multiple dots
.replace(/(.+)-/g, "$1") // invalid signs
.match(/^(-?)(.*?)((?:\.\d*)?)$/);
let pos = foo.selectionStart - 1;
if(!integer && decimals) pos += 2;
// don't convert an empty string into a 0,
// unless there are decimal places following
if(integer || decimals) {
integer = +integer;
}
const formatted = sign + integer + decimals;
if(formatted !== value) {
foo.value = formatted;
foo.setSelectionRange(pos, pos);
}
}
<input type="text" id="foo" />

Add Comma after thousand number not for decimal numbers

I am adding a comma to thousand number but those numbers have decimal value so that decimal value also added comma which I don't want
Eg: default number 2476.570550272 and I want to add comma 2,476.570550272
After using the below code I am getting comma to decimal number also like this 2,476.570,550,272.
$.fn.digits = function () {
return this.each(function () {
$(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
$(".number").digits();
Javascript has a function for this, it's called NumberFormat:
const number = 123456.789123123123;
const yourFormat = new Intl.NumberFormat('en-EN',{ maximumFractionDigits: 5 });
console.log(yourFormat.format(number));
The function is very versatile, here you can find more options. I suggest a read for what it can do for future usage also. It has many options and is also very recommendable for currencies.
Try with this.
function numberWithCommas(ADD-YOUR-NUM-HERE) {
var parts = number.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
Here's a vanilla-flavored adaptation of your regex that works as you specified.
digits(document.querySelectorAll(".numInput"));
function digits(inputs){
for(let input of inputs){
const [int, dec] = input.value.split(".");
input.value = int.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + (dec ? "."+dec : "");
}
}
<input class="numInput" value="4321.09876" />
<input class="numInput" value="987654321" />
<input class="numInput" value=".123456789" />

Check only numbers used in input field

I have a simple if statment in a verify function that check at least 10 numbers are used in a field
function verfiyFields() {
var flag = true;
var number = $atj('#interested-number-form');
if(number.val().replace(/\s+/g, '').length < 10){
number.parent().prepend('<p class="form-error">Please enter phone number</p>');
fadeOut();
flag = false;
}
return flag;
}
How can I also check that only numbers are used.
You could use .match(/^\d+$/) to check if there are only digits.
var value = number.val().replace(/\s+/g, '');
if (value.length >= 10 && value.match(/^\d+$/)) {
// ..
}
You can also check if there are at least 10 digits using the regular expression /^\d{10,}$/ and avoid checking the length property:
var value = number.val().replace(/\s+/g, '')
if (value.match(/^\d{10,}$/)) {
// ..
}
As a side note, you can also use the pattern attribute:
<form>
<input type="text" pattern="^\d{10,}$" />
<input type="submit" />
</form>
function verfiyFields() {
var reg = /^\D*(?:\d\D*){10}$/;
var number = $atj('#interested-number-form');
var flag = reg.test(number.val())
if (!(flag)) {
number.parent().append('<p class="form-error">Please enter a valid 10 digit phone number</p>');
}
return flag;
}
Use RegExp.test(str) to check to make sure that the length of the field excluding all characters that are not digits is 10. RegExp.test returns a true or false value so this can be the flag you return.
RegExp.test(str) Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Demo:
http://jsfiddle.net/SeanWessell/1v6vnath/

check if a given value is a positive number or float with maximum two decimal places

I am trying to implement a validation check for an input text control which should allow only a positive integer value or a float with maximum 2 decimal places.
Here is the fiddler with the approaches I've tried: https://jsfiddle.net/99x50s2s/49/
HTML
Enter Price: <input type="text" id="price"/> (Example: 10, 10.50. Do not include $ symbol.)
<br/>
<br/>
<button type="button" id="check1">Check Method 1</button> (Fails when the value is 1.00)
<br/>
<br/>
<button type="button" id="check2">Check Method 2</button> (Passes when the value is 45f)
<br/>
<br/>
<button type="button" id="check3">Check Method 3</button> (Passes when the value is -10)
Code:
var price = $('#price');
$('#check1').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (String(num) === val && num >= 0)
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check2').on('click', function(){
var val = $.trim(price.val());
var num = Number(val);
if (((typeof num === 'number') && (num % 1 === 0)) || parseFloat(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
$('#check3').on('click', function(){
var val = $.trim(price.val());
if ($.isNumeric(val))
{
alert('Valid');
}
else
{
alert('Invalid');
}
});
Expectation:
The values that should be passed are positive numbers and float with maximum 2 decimals. (example 10, 10.50)
I looked at various answers in stackoverflow but non matched with my expectation. Any help is appreciated.
What you are really looking for is that the value matches a pattern, not what it's value is. For that, you are probably best off using a regular expression. Specifically, this should catch the value that you are looking for:
/^\d+(\.\d{1,2})?$/
That says:
starting at the beginning of the value (^)
match 1 or more digits (\d+)
followed by an option decimal point and 1 or two digits ((\.\d{1,2})?)
and no other characters before the end of the value ($)
That should enforce all of your rules, allowing you to perform a single check for validity, rather than multiple ones.
Edit: Here is an example of how to use it:
function checkNumber(sNum) {
var pattern = /^\d+(\.\d{1,2})?$/;
console.log(sNum + " is " + ((pattern.test(sNum)) ? "" : "not ") + "valid.");
}
checkNumber("1"); // 1 is valid.
checkNumber("-1"); // -1 is not valid.
checkNumber("1234"); // 1234 is valid.
checkNumber("1."); // 1. is not valid.
checkNumber("1.0"); // 1.0 is valid.
checkNumber("1.12"); // 1.12 is valid.
checkNumber("1.123"); // 1.123 is not valid.
I would imagine it would be:
var num = Number(val);
if (!isNaN(num)
&& num > 0
&& num == num.toFixed(2))
{
// Valid
}

Decimal validation in the textfield using javascript or jquery [duplicate]

This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 9 years ago.
i Want to validate a text field in keyup event .
in the field it should accept money type decimal like
(12.23)
(.23)
(0.26)
(5.09)
(6.00)
if i enter some wrong value then it should return to the previous value and remove the wrong one
I think something like this might be your best bet
var isValidCurrency = function(str) {
var num = parseFloat(str);
return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};
Some tests
isValidCurrency("1234.56"); // true
isValidCurrency("1234.565"); // false
isValidCurrency("1234"); // false
isValidCurrency("foo"); // false
You can use following Regex
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
http://jsfiddle.net/rtL3J/1/
EDIT
Please note that if the numbers preceding dot (.) has limit of length to two then the code valid code is
^(\d{0,2})(\.\d{2})$
else if there is no limit then just remove the 2 from the code i.e.
^(\d{0,})(\.\d{2})$
Try this:
function evMoneyFormat(evt) {
//--- only accepts accepts number and 2 decimal place value
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
if (!regex.test(key)) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
The control:
<input type='text' onkeyup='evMoneyFormat( e );'>
Try following code
function validateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
And in html
<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />

Categories