Only allow a single dot point in input field - javascript

I have an input field which has:
$(".double").alphanumeric({allow:" ",ichars:"`~!##$%^&*=_+[]\\{}|;\":,/<>?'-()\/abcdefghijklmnopqrstuvwxyzABCDFEGHIJKLMNOPQRSTUVWXYZ"});
validation applied to it.
I need to further restrict entry so that only a single decimal place can be added e.g. 100.00 or 255.95
The input is used for currency so I need to only allow 1 decimal point. At the moment its allow 100.00.00 which messes up the system!
Thanks

Here is a regex that will only allow positive/negative decimal numbers
^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$
With jquery you can test the value
if (/^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$/.test($(".double").val())) { .... }

A simple function to allow an optional leading + or - and only digits with an optional decimal place is:
function validate(value) {
var re = /^[-+]?\d+(\.\d+)?$/;
return re.test(value);
}
However since you want money, you might want:
var re = /^[-+]?\d+(\.\d\d)?$/;
which will require two digits after the decimal place, if there is one.

Related

How to use Regex to limit user input to numeric fields, with one allowed decimal and one allowed negative symbol in front

I am trying to only allow numeric values, along with a possible negative symbol at the front of the string, and a single decimal, using Regex in JavaScript. This input value will only allow for a possible 10 digits also.
Currently, when a user inputs text, I have this logic that will only allow numbers, negative signs, and decimals. However, I want to limit the number of the negative sign to one, and only allow this at the front of the string. Also, I want to limit the number of decimals to one.
input.slice(0, 10).replace(/[^0-9.\-]/, '');
Can anyone please help me figure this out?
You can do:
input.slice(0, 10).match(/([-]?)([0-9]+)([.]?)([0-9]?)/);
Short n sweet.
/^-?\d{0,10}(\.\d{0,3})?$/
optional negative char. at the start
allows max of 10 digits next
again optional decimal group with at most 3 decimal places
These barriers can be modified accordingly.

regex check for Float number -> not ending and stars with decimal point

I am facing issues with regex pattern for Float number -> that should not end or stars with decimal points..
I have tried following regex patter.. that is
regex = /^\d*\.?\d*$/
// on doing
regex.test(11.)
regex.test(.11)
// it is returning true in checking
// I need to make this as false, comment will be much helpful
thank you.
You should bear in mind that regex only works with strings. When you pass a non-string variable as input to a RegExp, it will first coerce it to a string type.
Have a look:
console.log(11. , 'and', .11); // => 11 and 0.11
So, the actual string values you pass to your ^\d*\.?\d*$ regex are 11 and 0.11 that can be matched with the given pattern. Actually, ^\d*\.?\d*$ is a regex that is usually used for a very loose live number input validation, e.g. see How to make proper Input validation with regex?.
What you want is to implement a final, on-submit validation pattern, so that it could not pass strings like 11. and .11. There have been lots of threads discussing this kind of regex:
Regular expression for floating point numbers
regular expression for finding decimal/float numbers?
Basically, for validation, you will need something like
/^\d+(?:\.\d+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]{1,2})?$/.test(input_string) // Some need to only allow 1 or 2 fractional digits
/^[0-9]{1,3}(?:\.[0-9]{2})?$/.test(input_string) // 1-3 digits in the integer part and two required in the fractional part

Regex to make nondecimal number decimal (add .00)

I have an user input where user can edit price of something. To leave data consistance I would like to manipulate with that string on front-end site.
What I want to do is:
1234 to 1234.00
12.3 to 12.30
12,3 to 12.30
1234.45 to 1234.45
So basicly,
Replace comma with dots
this should be done easy with somehing like:
str.replace(',', '.');
Add dots if number if not decimal and also always change number of digits on two(so add 0 if needed)
I try to do something like:
priceByUser = priceByUser.replace(/^\d*\.?\d*$/, "$1\.00");
unfortunately this really doesnt even work as I expected.
Is there a chance someone can help me to solve this issue?
Thanks
You could consider using a regular expression to replace your commas and periods with just decimal points and then parse the values as floats via parseFloat() then finally, use the toFixed(2) function to indicate that you want two decimal places :
// This will clean up your input (consolidating periods and commas), parse the result
// as a floating point number and then format that number to two decimal places
priceByUser = parseFloat(priceByUser.replace(/,/g,'.')).toFixed(2);
If you wanted an extra-level of validation, you could consider stripping out any non-digit or decimal places after this occurs :
// Sanitize
priceByUser = priceByUser.replace(/,/g,'.').replace(/[^\d\.]/g,'');
// Parse and format
priceByUser = Number(priceByUser).toFixed(2);
Example
You can see a working example here and and example of input/output below :

Number Restriction after decimal point in javascript

How to restrict the number of digits after the decimal point using "onkeyup" even in javascript?
I want to restrict the number of digits after the decimal point based on an input already given in the page. if i give the input as 3 then the digits after the decimal points should be only 3. for this i need to use javascript so that at runtime itself output is shown to user and the user should not be able to enter more than 3.
You can use the toFixed method:
var withDecimals = (1*value).toFixed(numberOfDecimals);
Multiplying by 1 makes sure that we are dealing with a number and not some other object, like a string.
Try this:
your_number = (your_number).toFixed(3);
You can use toFixed(Your number) for that
The objectvalue is the current inputtext object where value is entered. id is the object value of the field where precision(no of digits after decimal) is entered.
function decimalRestriction(objectValue,id)
{
var precision=document.getElementById(id).value;
var value=objectValue.value;
if(value.match('.'))
{
var decimaldigits=value.split('.');
if(decimaldigits[1].length > precision)
objectValue.value= decimaldigits[0]+ '.' + decimaldigits[1].substring(0, precision);
}
}

Add comma separator to a value variable

I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable
x = 10023871234981029898198264897123897.231241235
How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string.
First of all, for such huge numbers you should use string format:
var x = "10023871234981029898198264897123897.231241235";
Otherwise, JavaScript will automatically convert it to exponential notation, i.e. 1.002387123498103e+34.
Then, according to the question about money formatting, you can use the following code:
x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
It will result in: "10,023,871,234,981,029,898,198,264,897,123,897.231241235".

Categories

Resources