Please help with me writing a JavaScript Validation for currency/money field.
So please provide any regular expressions if u have :)
Also, for my region, don't need any currency symbols like '$' in the field.
Only decimals are to be included for validation as special chars., along with numbers.
You could use a regexp:
var regex = /^\d+(?:\.\d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
alert("Number is valid");
If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:
var numStr = "123.20";
var numNum = +numStr; // gives 123.20
If the number string is invalid, it will return NaN (Not a Number), something you can test for easily:
var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
alert("numNum is not a number");
It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2) to round to 2 decimal places. parseFloat is much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc") would yield 123.
I built my answer from the accepted answer.
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
^[1-9] The number must start with 1-9
\d* The number can then have any number of any digits
(...)$ look at the next group from the end (...)$
(...)?(...)? Look for two groups optionally. The first is for the comma, the second is for the decimal.
(,\d{3}){1} Look for one occurance of a comma followed by exactly three digits
\.\d{0,2} Look for a decimal followed by zero, one, or two digits.
This regex works off of these rules:
Valid values are numbers 0-9, comma and decimal point.
If a customer enters more than one decimal point or more than one comma, the value is invalid and will not be accepted.
Examples of invalid input values
1.2.3
1,2,4
Examples of valid input values
1.23
1,000
3967.
23
1.2
999,999.99
An example can be seen here:
http://jsfiddle.net/rat141312/Jpxu6/1/
UPDATE
by changing the [1-9] in the regex to [0-9] any number less than 1 can also be validated. Example: 0.42, 007
/[1-9]\d*(?:\.\d{0,2})?/
[1-9] - must start with 1 to 9
\d* - any number of other digits
(?: )? - non capturing optional group
\. - a decimal point
\d{0,2} - 0 to 2 digits
does that work for you?
or maybe parseFloat:
var float = parseFloat( input );
let amount = document.querySelector('#amount'), preAmount = amount.value;
amount.addEventListener('input', function(){
if(isNaN(Number(amount.value))){
amount.value = preAmount;
return;
}
let numberAfterDecimal = amount.value.split(".")[1];
if(numberAfterDecimal && numberAfterDecimal.length > 3){
amount.value = Number(amount.value).toFixed(3);;
}
preAmount = amount.value;
})
<input type="text" id="amount">
For me its working fine for Indian currency in INR
var regex = /^[1-9]{0,2}(,{0,1})(\d{2},)*(\d{3})*(?:\.\d{0,2})$/;
var a = '1,111.11';
regex.test(a);
Now I use this:
let func = function (vStr) {
let v0 = Number(vStr);
let v1 = Number(v0.toFixed(2));
return v0 === v1;
};
Note that, NaN === NaN returns false. Maybe some substitution for '$' and ',' before parsing is needed, for other cases.
And there is a problem of precision for very large number, longer than 16 digits. As well as values of '0x3a', '68n' is considered valid.
Nowadays, <input> of type="number", with step='.01' may be more proper.
Related
I am trying to write a regex for the following condition:
Allow to enter up to 1 decimal place and if I start with integer 0; the next has to be decimal otherwise any other number entered will remove the 0(integer)
The regex that I have provided is /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/ it accepts 1 decimal place but I am unable to achieve the remaining part.
Edit 1
passed numbers -->
1.3
4.5
0.4
Failed numbers ---->
004
If number starts with 0, next character must be a decimal only
Eg,
0.5 is a pass
005 is a failed
try this:
^([1-9]+\d*.?\d?)|^(0.\d)
If not, see comments and try to better exemplify
Try this regex:
^([0]{1}(\.[0-9]+))$|^([1-9]{1}|[1-9][0-9]+)$
ADJUSTED REGEX:
I have now adjusted the regex as required: all numbers that start with 0 MUST follow a comma, e.g. 0.2 or 0.0002 is accepted. 02 or 00002 is NOT accepted
OK, you want find integer number not start with 0, and find decimal?
Your code is: /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/
Case 1: integer [1-9]\d*
Case 2: decimal
//match 5.0
patt = \d+\.\d+
//Match 5.1xxxx, 5.2xxx, etc.
patt = \d+\.[1-9]\d*
//match 5.0xxx
patt = \d+\.0\d+
//combine all of them
patt = ([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)
//Final
patt = /(^$)|(([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)?$)/
I will explain some pattern above:
\d == [0-9] //match 1 character between 0 and 9
\d* == \d{0,} //match 0 or more character
\d+ == \d{1,} //match at least one character
I want number in this format
(123)-456-7890
The maximum length assigned is 10.
The regular expression used to obtain the above format is:
if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
If length>10 I want the above format for the number and to ignore the rest of the digits(right trim).
How can I do that?
If you remove the if condition and add a "catch-all" regex .* at the end, it will ignore whatever comes after the 10th digit:
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4}).*/, '($1) -$2-$3');
This assumes that onlyNums actually contains nothing but digits (and at least 10 of them). Otherwise, the result might be unexpected.
Test it live on regex101.com.
I would like to know if there is a simple approach to split units and quantities apart in a string notation, where the unit is optional.
entry examples: 10, 20kg, 14h, 5;
What would you use to split for example the 20kg into 20 and kg etc?
*edit: in my examples list I didn't include decimal values, but those are also possible. (0.1 or 1.25 euro)
var string="10kg"// string="10kg"
var number=parseInt(string);//number=10
var unit=string.substr(parseInt(string).toString().length);//kg
You could use regex to split your quantities...
.match(/(\D*)(\d+)(\D*)/)
...will split your text into an array of 4 elements, the first of which will contain the original string followed by the groups of prefix, numeric value, and the suffix.
Zero or more non-digits followed by one or more digits followed by zero or more non-digits.
Here is an example, check the console:
var input = ['20kg', '40m', '$10', '50 km', '20'],
result = [];
input.forEach(function(elem) {
result.push(elem.match(/(\D*)(\d+)(\D*)/));
});
console.table(result);
You can account for the decimal places as well by changing the middle group to:
(\d+(\.\d+)?)
Digits followed by a dot and then digits if present.
I am trying to build a regex expression with this requirement .
Requirement :
Max length - 5(inc decimal dot if is a decimal number)
Decimal precession - max 2 digits (if it is a decimal numer ).
Number - need not to be a decimal number (not mandatory)
Code:
<script>
function myFunction() {
var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
var num = 12345.52; // i will test here indiffernt ways
var n = regexp.test(num)
document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>
Output should look like :
12345.52 -->It should return false as length is 8 inc dot but it returns true
123456.52 --> false . I came to know d{0,5} is looking for before decimal
12.45 --> true . Perfect one (length 5 , precession 2 )
12345 --> true . Perfect one (length 5 , precession- not madatory)
I am hoping to build a regex expression satisfies all the above scenarios .
Reference : Click Here
You could try the below regex which uses positive lookahead assertion.
^(?=.{1,5}$)\d+(?:\.\d{1,2})?$
DEMO
Explanation:
^ Asserts that we are at the start.
(?=.{1,5}$) Asserts that the length must be from 1 upto 5.
\d+ Allows one or more digits.
(?:\.\d{1,2})? Optional decimal part with the allowable digits after the decimal point must be one or two.
$ Asserts that we are at the end of the line.
What I want is, there is a textbox with maximum length of 5. The values allowed are..
any integer // for example 1, 3, 9, 9239 all are valid
real number, with exaclty one point after decimal // eg. 1.2, 93.7 valid and 61.37, 55.67 invalid
it is also allowed to enter only decimal and a digit after that, that is .7 is valid entry (would be considered as 0.7)
I found this page, http://www.regular-expressions.info/refadv.html
So what I thought is that
There is a digit
If there is a digit and a decimal after that, there must be one number after that
If there is no digit there must be a decimal and a digit after that
So, the regex I made is..
a single digit one or more => /d+
an optional decimal point followed by exactly one digit => (?:[.]\d{1})?
if first condition matches => (?(first condition) => (?((?<=\d+)
then, match the option decimal and one exact digit =>(?((?<=\d+)(?:[.]\d{1})?
else => |
find if there is a decimal and one exact digit => (?:[.]\d{1}){1}
check the whole condition globally => /gm
overall expression =>
(?(?<=\d+)(?:[.]\d{1}){1}|(?:[.]\d{1}){1})+/gm
But it doesn't outputs anything..
Here's the fiddle
http://jsfiddle.net/Fs6aq/4/
ps: the pattern1 and pattern2 there, are related to my previous question.
Maybe you are complicating things too much. I did a quick test and unless I'm missing something this regex seems to work fine:
/^\d*\.?\d$/
Demo: http://jsbin.com/esihex/4/edit
Edit: To check the length you can do it without regex:
if ( value.replace('.','').length <= 5 && regex.test( value ) ) {
...
}
Notice that I used replace to remove the dots so they don't count as characters when getting the length.
You can try the following pattern:
/^\d{0,4}\.?\d$/
It seems to fulfil all your requirements:
> /^\d{0,4}\.?\d$/.test(".4")
true
> /^\d{0,4}\.?\d$/.test(".45")
false
> /^\d{0,4}\.?\d$/.test("1234.4")
true
> /^\d{0,4}\.?\d$/.test("12345.4")
false
> /^\d{0,4}\.?\d$/.test("12345")
true
> /^\d{0,4}\.?\d$/.test("123456")
false
This pattern assumes that the number can have a maximum of five digits and an optional decimal point.
If the maximum length of five includes the optional decimal point then the pattern is slightly more complex:
/^(?:\d{1,5}|\d{0,3}\.\d)$/
The first part of the group deals with integer numbers of the required length, the second option of the group deals with real numbers which maximum length (including the decimal point) is five.
Consider this code:
var checkedString = "45.3 fsd fsd fsdfsd 673.24 fsd63.2ds 32.2 ds 32 ds 44 fasd 432 235f d653 dsdfs";
checkedString = " "+checkedString;
var results = checkedString.match(/[\s]{1}(\d+\.*\d{1})(?![\d\.\w])+/gm);
results.map(function(result) {
return result.trim();
});
Couldn't make it in other way because in JS (?<= (lookbehind) regexp is not working.
This will be returned:
["45.3","32.2","32","44","432"]
So probably it's what you've expected.
I don't know what are you trying to do with those conditionals in your regex. I also looked at your jsfiddle, which outputs nothing for me. But I made a two versions of a regex that matches the correct values for the textbox, which are ^(?!(.{6,}))(?:[1-9]\d*)*(?:\.\d*[1-9])?$ and ^(?!(.{6,}))(?:\d*)*(?:\.\d*)?$.
The first disallows to start with zero, or end with zero after the decimal.
Comment if you need explanation of the regex.