Convert int with starting zeros to string to check length - javascript

I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?

I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.

Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">

You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)

<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max

You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.

Related

How to restrict the user to not enter more than 8 numbers?

here is my implementation
//I restrict the user to enter number only
if (isNaN(e.target.value)) {
e.target.value = e.target.value.substring(0, e.target.value.length - 1)
e.target.type = 'number'
}
// here I forced the user to enter only 8 numbers
if (e.target.value?.length > 8) {
e.target.value = e.target.value.substring(0, 8)
}
The above code works sometime sometime not. I need an alternative. is there any alternative that would be great. Thanks
You can use String's substr method, to extract only 1st 8 characters, if length of input is greater than 8.
You also need to set max="99999999" on input so that input doesn't go beyond 99999999 upon clicking <input>'s arrows.
let input = document.querySelector(".num");
input.addEventListener("input", ()=>{
if(input.value.length > 8){
input.value = input.value.substr(0,8);
}
});
<input type="number" max="99999999" class="num">
Why dont you make it simpler
<input type="number" onKeyPress="if(this.value.length==8) return false;" max="99999999"/>
type ="number" are used to let the user enter a number. They include built-in validation to reject non-numerical entries.
learn more here

How to automatically add comma on amount displayed in input field if the customer clicked a button with specified amount?

The customer may click a button with specified amount and the amount would display in input field. I'm trying to automatically add a comma on the displayed amount but it's only working if the amount is typed. What would be the easiest way to do it?
<input type="number" class="input-char-amo" id="d-total" step="10000" value="0" min='10000' max="5000000" / required>
https://codepen.io/Cilissaaa/pen/vYYGjYB
You could use toLocaleString() method. It returns a string with a language-sensitive representation of a number.
let n = 1000000;
n.toLocaleString(); //"1,000,000"
chek it once. Hope it helps.
I have found the solution on this link: Can jQuery add commas while user typing numbers?
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">

Limit the input Field to take only numbers with range

I want to create a input field in html where can limit the users to enter a number only between the range -40 to 130.
The user can also enter decimal values
For example :
-40.2 (valid)
-40.23 (not Valid)
130(valid)
130.1 (not Valid)
So the input should be able to take in any number between the range and should only accept decimal place fixed to 1.
Any suggestions or help is highly appreciated
thanks in Advance
You can use an input of type number with the attributes min max and step like this :
<form action="">
<input type="number" min="-40" max="130" step="0.1" id="input"/>
<button type="submit">Ok</button>
</form>
I provide a JSFiddle here. When you try to submit the form, the html5 validation displays a message if the number is out of the bounds or with more than one decimals.
JSFiddle
as Xartok told You can use an input of type number with the attributes min max and step but if the user is keying in the input its a bit hard from my experience. what i did was like this.
onkeypress is used to allow users to only key in integers with decimal only.
ng-blur is used to trigger changeDecimal function to do the validation/rounding up to fixed decimal places
<form>
<input type="text" id="input" onkeypress="return event.charCode >= 45 && event.charCode <= 57 && event.charCode!=47" ng-model="input1"ng-blur="changeDecimal()" />
<button type="submit">Ok</button>
</form>
and from the controller side what i did was this :
1st i parse the input to float and fix it to 1 decimal place.
then i made a condition to check the range if it is within the range, the input is replaced with the new value else an alert is returned.
in the else section i did a small check if the input is blank or not a number then replace with a default value (to avoid a loop of alert if the input is left blank)
app.controller('MainCtrl', function($scope) {
$scope.changeDecimal = function (){
temp = parseFloat($scope.input1).toFixed(1);
if (temp > -40 && temp < 130 && !isNaN(temp)){
$scope.input1= temp;
}else{
alert("value out of range ");
if (isNaN (temp) || temp == null || !angular.isDefined(temp)){
$scope.input1=0;
}
}
}
});
If you plan to use the input type as number what you can do is set a condition for you submit button (ng-disable). the button is disabled until the condition is met.
here is the sample from Plunker

jQuery: how to set fixed decimals for input field value

I have a basic input field in which an amount is to be filled in.
The field is formatted as text as it also has to work with older browser versions.
Is there a way I can use jQuery and/or Regex to set fixed decimals (2) to any number in this field ?
I tried the following but this doesnt change anything:
<input type="text" class="span6" id="amount" maxlength="12" name="amount" />
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^\d+$/) ) {
$('#amount').val( amount.toFixed(2) );
}
});
What I am looking for is a way to add two decimals to the input value if there are none and the input is a number.
Examples:
1000 should become 1000.00
1000.99 should stay 1000.99 as there are already two decimals.
Many thanks for any help with this, Tim.
I have created a fiddle, please check Fiddle
before using toFixed convert the amount to integer parseInt(amount).
Edit
Code
$('#amount').on('blur', function() {
var amount = $('#amount').val().replace(/^\s+|\s+$/g, '');
if( ($('#amount').val() != '') && (!amount.match(/^$/) )){
$('#amount').val( parseInt(amount).toFixed(2));
}
});

Restrict numbers and limit them to two

How to restrict my text field to numbers only and limit them in two with a single function.
Since no one has suggested a regular expression, I will. :-)
var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
// number is one or two digits with optional leading minus
} else {
// it's not
}
For limiting them to enter only 2 char use maxlength attribute of input. To check enter string is number or not user isNaN(str) function.
<script type="text/javascript">
function ValidateField(FieldName){
// Get fields value
var FieldVal = document.GetElementById(FieldName).value;
// Check it's a number, and then check it's range is correct
// Alternatively you could do FieldVal.length
if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
alert("Valid!");
else
alert("Invalid");
}
</script>
<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>
I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.
In HTML5 you can just use: <input type="number" />
If you are using jquery:
$('#myTextAreaID').keydown(function(event) {
if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105

Categories