How to validate a decimal value input? - javascript

Currently working on only decimal values where in the text field user enter only deciaml value. Should accept only 10 numbers for example if user enter 12345.000000 it should get an alert says Number field format error. Please re-enter using the proper format. (6.3)
With my current jquery code it will accept decimal value
$("#txtQty").keyup(function() {
var $this = $(this);
$this.val($this.val().replace(/[^\d.]/g, ''));
});
This is my html code for the text box with this html it will allow only 10 character
<input id="txtQty" type="text" maxlength="10"/>
I tired the below SO user told but still I am getting the same issue
$('#txtQty').focusout(function(e) {
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
}
});
before decimal point it has to accept (1-6) 6 number after decimal point it has to accept 3 only zero's if wrongly typed it should throw an alert not at all working still not getting that
Here is the fiddle link for the same
123456.000 -- true
12345.000 -- true
1234.000 -- true
123.000 -- true
12.000 -- true
1.000 -- true
Thanks in advance
$('.ipt_Havg').focusout(function (e) {
var regexp = /\d*\.\d{3}/
if (document.getElementById("ipt_Havg").value !== regexp) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
});

1) Your if/else is broken...
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null // <- comparison makes no sense here
}
You are incorrectly using a comparison operator in place of a "statement" within the else. The else needs to contain a "statement" (something to do) not another comparison operator.
See: MDN "if...else" documentation
If some condition is true then do something, otherwise do something else.
if ('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
2) NOTE: I previously thought this was too obvious to even mention, however, you've hard coded '123456.789' into the conditional. In other words, it will never matter what value gets entered into your form...
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) is always going to be true since '123456.789' is the only value being used here.
Otherwise, use the value of the field...
$('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null
3) Your logic was also backwards.
if ($('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null) {
alert('nothing wrong here');
} else {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}
DEMO: http://jsfiddle.net/wfzv0h5y/
4) Incorrect regex...
but one small mistake in the end it has to accept only three zero not more than tht but now if i enter 1234.0000 still it was accepting
Your regex also needed fixing...
^\d{1,6}\.0{3}$
DEMO: http://jsfiddle.net/wfzv0h5y/6/

JQuery Number Formatter Plugin is a good alternative in your situation.
https://github.com/andrewgp/jsNumberFormatter
You can check your input through this and validate the way you want.

You could use HTML5 input number:
<input type='number' step='0.001' max="999999.999" />
The step= sets the decimal places, the max= guarantees the other side.

You can specify repetitions in RegExps:
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
true
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
false

Related

How to replace an input text value in order to match a currency type input

I have a complex problem with a simple input. I want the user to enter an amount of money, so I naturally thought of using a number type. The problem is that I live in Europe and decimals are written with commas(and so the number input will automatically add a comma as separator), but my backend logic expects dots for the cents.
After looking everywhere for alternatives to this problem, I only found I could use a text input and check the user's input with a chain of .replace to test that the user is only entering numbers and eventually a dot followed by only two numbers for the cents.
This is the code we created so far:
export const onChangeCustomInput = (e) => {
let value = e.target.value
value = value
.replace(/[A-Za-z]+$/g, '')
.replace(/,/g, '.')
.replace(/ /g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
.replace(/[.\s]{2,}/, '.')
.split('.')
if (typeof value === 'object' && value.length > 1) {
value[1] = value[1].substr(0, 2)
if (value.length === 3) {
value.splice(2, 1)
}
value = value.join('.')
}
e.target.value = typeof value === 'object' ? value[0] : value
}
this is very heavy (and ugly) code, and Sonar check failed saying this may lead to Denial of Service attack (?...).
Is there a better way to manage this case in vanilla javascript?
Can you try toLocaleString?
Basically if you have a number You can set in which kind of country you're using it.
So, you can show as an EU number, but send to the backend in the other format.
One example:
var number = 35001235.12
number.toLocaleString('en-US') // returns '35,001,235.12'
number.toLocaleString('de-De') // returns '35.001.235,12'
You can read more in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
You could try using valueAsNumber property of the input element. The value is numeric so it shouldn't matter what was entered by the user. If the input is wrong it takes the value of NaN.
You can use the package Inputmask, it works perfect for your use case, you will use this regex [0-9]*\.[0-9]{2} to match your example
$(document).ready(function(){
Inputmask().mask(document.querySelectorAll("input"));
});
<script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.js"></script>
<input data-inputmask-regex="[0-9]*\.[0-9]{2}" />

toString().length on a number with zeros and only zeros always returns 0

I'm working on a page that accepts 4 digits (exactly 4 digits) pin from users. Something like this.
<input type="number" ng-model="passCode" class="form-control" onpaste="return false" id="passCodeField" ng-disabled="!enablePassCode" ng-change="onInputPasscode()" ng-keypress="onKeyPressPasscode($event)"/>
onKeyPressPasscode function
$scope.onKeyPressPasscode = function($event) {
if(isNaN(String.fromCharCode($event.which || $event.keyCode))){
$event.preventDefault();
}
}
onInputPasscode() function :
$scope.onInputPasscode = function() {
if ($scope.passCode.toString().length > 4){
$scope.passCode = $scope.passcode;
}
if($scope.passCode.toString().length == 4) {
$scope.passcode = $scope.passCode;
$scope.disableContinue = false;
session.put('pinFlow',true);
} else {
console.log("current length - " + $scope.passCode);
$scope.disableContinue = true;
session.put('pinFlow',false);
}
}
This is failing when the input is all zeros. i.e current length is not getting updated hence the user is allowed input as many zeros as he wants. How do I take 4 digit zeros as input and still meet the checks that I have?
This is in angular 1.5.8v. And I'm not an expert in AngularJS. So any help would be appreciated. Also, please let me know if need any other info. I'll update the answer accordingly.
Thanks in advance.
It's not possible to do this with a an input with type set to number.
When user enters a number 0001, that's actually 1.
Things like PINs should be handled with type set to text.
You can then use a regex for validation.
To allow exactly four digits, no more and no less, use the following regex:
^\d{4,4}$
From JavaScript, use this regex to test a string, like the following:
/^\d{4,4}$/.test('1234')
// => true
/^\d{4,4}$/.test('123456')
// => false
/^\d{4,4}$/.test('12')
// => false
The cause of your problem is that if you PIN Scheme allows for leadings zeros, number is not the ideal type for this (because in numbers, leading zeros can be omitted without changing meaning).
Instead, use input type=text or probably even better, input type=password. Also, I wouldn't listen to keypress - instead use the input event.

Decimal Field Validation in Textbox with Jquery or Javascript

I searched on the forum but didn't find the correct answer.
What I am trying is
Textbox which accepts decimal numbers, so user should be able
to enter either 0 or 1 decimal point ie. dot(.)
at the max 5 digits before the dot and at the max 5 digits after the dot
no other character should be allowed, but arrow keys and other keys like f1 f2 should work
eg. it should be valid for following
12345
12345.1
12345.12345
1.12345
.12345
Need help in making this textbox.
Try this:
function isFloat(s) {
return s ? /\d{1,5}(?:\.\d{1,5})?/.test(s) : true;
}
$('input.float').on('change', function() {
if (!isFloat($(this).val())) {
alert('not a float');
}
});
And here's the fiddle: http://jsfiddle.net/foxbunny/Vabj4/
The code doesn't make the field required. If it's empty, it'll just pass. If you can change that by changing true in the ternary conditional to false (line 2).
EDIT:
Oh, and if you want to restrict input to certain keys, you should reconsider. It's not a very good user experience. People are used to typing just about anything. It's best to just warn them. It's cheaper to do and it's effective enough:
http://jsfiddle.net/foxbunny/Vabj4/1/

Validating text input as a number - JavaScript

I am trying to validate user input to make sure that what they type (if anything - field is not required) is a number. Now I don't care what this number is, but it must be an integer. Negative, positive, whatever is validated later on. Here is my test sample so far:
var a=["",0,"0",-2,"-2",2,"2",-2.2,"-2.2",2.2,"2.2",-1,"-1",undefined,null,NaN,Infinity,-Infinity],x;
for(x=0;x<a.length;x++){
console.log(a[x],(isNaN(+a[x]) || Math.round(+a[x]) != +a[x] || +a[x] === null || +a[x]+1==+a[x])?false:true);
}
If you run that in a console, it shows true for any element in a which would pass the validation, false otherwise. This validation works as expected for me in Chrome (false is shown for all decimals, and everything from undefined onward.
My question is, will this work in all major browsers (IE 6+ included), and have I completely checked this against every possible input?
As a note:
+ is used in front of the a[x] for type-converting (and also trimming strings - " 2 " gets converted to 2.
The last check, +a[x]+1===+a[x] is what checks against (+/-)Infinity.
Thanks :) .
Try this function
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
alert("Is an Integer");
} else {
alert("Is not an Integer");
}
}
is_int(1); //Output - Is an Integer
is_int("a"); //Output - Is not an Integer

Getting a integer value from a textbox, how to check if it's NaN or null etc?

I am pulling a value via JavaScript from a textbox. If the textbox is empty, it returns NaN. I want to return an empty string if it's null, empty, etc.
What check do I do? if(NAN = tb.value)?
Hm, something is fishy here.
In what browser does an empty textbox return NaN? I've never seen that happen, and I cannot reproduce it.
The value of a text box is, in fact a string. An empty text box returns an empty string!
Oh, and to check if something is NaN, you should use:
if (isNaN(tb.value))
{
...
}
Note: The isNaN()-function returns true for anything that cannot be parsed as a number, except for empty strings. That means it's a good check for numeric input (much easier than regexes):
if (tb.value != "" && !isNaN(tb.value))
{
// It's a number
numValue = parseFloat(tb.value);
}
You can also do it this way:
var number = +input.value;
if (input.value === "" || number != number)
{
// not a number
}
NaN is equal to nothing, not even itself.
if you don't like to use + to convert from String to Number, use the normal parseInt, but remember to always give a base
var number = parseInt(input.value, 10)
otherwise "08" becomes 0 because Javascript thinks it's an octal number.
Assuming you have a reference to the input text box:
function getInteger(input) {
if(!input || !input.value) return "";
var val = parseInt(input.value, 10);
if(isNaN(val)) return "";
else return val;
}
One thing you could do is a regex check on the value of the textbox and make sure it fits the format of an accepted number, and then if it fits the format perform your process, otherwise return an empty string.
Edit: This is an example from some code I have in front of me (might not be the best regular expression):
var anum=/(^\d+$)/;
if (!anum.test(document.getElementById("<%=txtConceptOrderValue.ClientID %>").value))
{
alert("Order Value must be a valid integer");
document.getElementById("<%=txtConceptOrderValue.ClientID %>").focus();
return false;
}
Edit 2: I should also note that I am using ASP.NET which is why I have the slightly funky way of accessing the textbox. In your regular JavaScript case it may not be as cluttered.

Categories

Resources