A convenient way to accept a fixed length number with decimal points - javascript

Basically I need to accept a simple decimal value string from a input box.
The length of the input is fixed to 5 digits so it is allowed to accept only 5 digit value.
But if the length of integer part is 5, it should be able to accommodate at least 2 more decimal points or should at least accommodate 2 decimal digits (excluding the decimal separator ) at any time.But the length of the integer part should not exceed 5 digits.
I thought used the following way :
//co2-weight is the class of input field
//by default the max-length and size is 6
$( '.co2-weight' ).keyup(function() {
if($(this).val().indexOf('.')>1)
{
$('.co2-weight').attr('size','9');
$('.co2-weight').attr('maxlength','9');
}
else
{
$('.co2-weight').attr('size','6');
$('.co2-weight').attr('maxlength','6');
}
});
But again here it need to check the length of integer part again and set it to 5.
Is there any shorter or convenient way ?
UPDATE:
The basic problem was to dynamically adjust the length in proper cases which are missing in the answers.

You could use this code, which will not allow:
more than 5 integer digits, nor
more than 2 decimal digits, nor
more than one decimal point, nor
any other character than digits or decimal point
It also applies the attribute changes dependent on whether there is a decimal point.
It responds to the input event, as there are ways of changing the contents without the keyup event firing (e.g. through context menu, mouse,or other device).
$( '.co2-weight' ).on('input', function() {
var good = $(this).val()
// remove bad characters and multiple points
.replace(/[^\d.]|\.(?=.*\.)/, '')
// remove any excess of 5 integer digits
.replace(/^(\d{5})\d+/, '$1')
// remove any excess of 2 decimal digits
.replace(/(\.\d\d).+/, '$1');
if (good !== $(this).val()) {
// Only if something had to be fixed, update
$(this).val(good);
}
var pointPos = good.indexOf('.');
// Determine max size depending on presence of point
var size = good.indexOf('.')>1 ? 8 : 6;
// Use prop instead of attr
$('.co2-weight').prop('size',size);
$('.co2-weight').prop('maxlength',size);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input class="co2-weight" size="6" maxlength="6">

This is the perfect case where you use regular expressions.
In your case this is the regular expression pattern that you need ^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$
In javascript you would use it this way:
$(this).val().match(/^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$/)
This line alone returns null if it does not find your match. An array of the matches if it does find a match.
If you need to test out this regular expression use https://regex101.com/

Using RegExp you can validate the format of the input like the following example ...
// regular expression to allow 12345.12
var regExp = new RegExp(/^\d{1,5}\.?\d{0,2}$/);
// initialize form elements
$('.valid').hide();
$('.invalid').hide();
$('.submit').prop('disabled', true);
$('.co2-weight').keyup(function() {
// on keyup validate against regular expression
if (regExp.test($(this).val())) {
$('.valid').show();
$('.invalid').hide();
$('.submit').prop('disabled', false);
} else {
$('.valid').hide();
$('.invalid').show();
$('.submit').prop('disabled', true);
}
});
$('.form').submit(function() {
// alert to show input was valid
alert('submitted');
});
.valid {
color: green;
}
.invalid {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something in the input to see if submit button become enable</p>
<form class="form">
<input type="text" class="co2-weight">
<input type="submit" class="submit">
</form>
<p class="valid">Input format is valid</p>
<p class="invalid">Input format must be <= 99999.99</p>

Related

Javascript RegExp should check four-digit input for plausibility

I want to program a JavaScript code which checks the input into an input field if it is a double two-digit HEX value. The input must contain exactly 4 digits and letters between a to f and/or 0 to 9. The following code leads to an error with a four digit input.
function check() {
var input = (document.getElementById("textField").value);
if (input.length == 4 && input.match([A-Fa-f0-9])) { alert("the input matches the requirements");}
else {alert("input is invalid");}
}
<input type="text" id="textField">
<button type="button" onclick="check()">check!</button>
If you are using regex you can define the length and simplify your test. You need to put your regex string in '/ /'.
if (input.match('/[A-Fa-f0-9]{4}/')) { ... }

How can I count the number of digits of a number with leading zeros in javascript?

I am taking a field value, that should be a 4 digit number.
I want to make sure that the value is a 4 digit number and if not, have a pop up that says "enter a 4 digit number".
I noticed that when I put the field value into a variable it does not take any of the leading zeros. The last test case I ran the code with was a value of '0000'.
var relay = this.getField("RELAY NUM").value;
var relayString = relay.toString();
var relaySplit = relayString.split("");
console.println("relay= " + relay);
console.println("string= " + relayString);
console.println("split= " + relaySplit);
for(i = 0; i < 4; i++){
if (relaySplit[i] >= 0) {
console.println("Looks good so far");
} else {
console.println("Please enter 4 digit number");
}
}
--------------------------------------------------------
relay= 0
string= 0
split= 0
Looks good so far
Please enter 4 digit number
Please enter 4 digit number
Please enter 4 digit number
true
Instead of traversing arrays, an approach you may want to consider is using a regex to determine whether the input value meets your criteria. Then on events such as keyup (using jQuery here but not necessary), you run the validation and apply styles, or send forth the popups as you wish. I put a limit on the length of the input so users are not able to enter MORE then expected input, but this isn't necessarily needed.
$("#input").keyup(function() {
let input = $("#input").val()
let isValid = validate(input)
$("#val").text(isValid ? "Valid" : "Invalid")
})
function validate(val) {
let x = /^[0-9]{4}$/
return x.test(val)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="input" maxLength="4" />
<label id="val"></label>
</div>

Allow digits to be replaced in a length-limited field

I am using a Regex to validate a number field. This allows only numbers in the field and the max length is 3 characters. Whenever there are 1 or 2 characters in the field and I select them by double clicking on them I am able to change the number by just pressing any other number.
However when the value contains 3 numbers, which is the max length of the field, when I select the number and try to input other number it doesn't work; I cannot input anything.
I thought this is an issue with the regex, but it's not. The issue is max length.
i tried changing max length whenever it hits the max length and I try to change it it doesn't work.
// Restricting negative numbers and special characters from qyt field and maximum digits to 3
$('.js-bundle-qty').on('keypress', function(event) {
if (event.keyCode != 8) {
console.log('demo');
var regex = new RegExp("^[0-9]{0,3}$");
var inputValue = String.fromCharCode(!event.keyCode ? event.which : event.keyCode);
var key = $(this).val();
key = key + inputValue;
if (!regex.test(key)) {
console.log('enter');
event.preventDefault();
return false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999">
https://jsfiddle.net/sanket4real/310sgheL/30/
To have the field show only integers and then allow the next pressed integer to force the oldest character from the value, or be replaced by selecting them you can use a regex to replace non-digit characters and slice() within an input event handler, like this:
$('.js-bundle-qty').on('input', function() {
$(this).val((i, v) => v.replace(/[^0-9]/g, '').slice(-3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999" length="3" />

How do I format my input field using replace regex with javascript and jQuery?

I want to format my <input id="phone_number" type="tel" name="phone_number" maxlength="14"> to have a value like this (123) 456-7890
My current jQuery code:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
var phoneNumberVal = jQuery("#phone_number").val();
var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(phoneNumberUsFormat);
}
});
The code above can format a phone number like this: (123) 456-7890 only after typing all the numbers.
What I want to happen is start adding a parentheses and a dash when the user reaches the 3rd and 6th digit
What I currently tried is this:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
if(phoneNumberVal.length < 4) {
newNumber = phoneNumberVal.replace(/(\d{3})/,"($1) ");
jQuery("#phone_number").val(newNumber);
}
}
});
The problem with the updated code above is not being able to detect the 6th digit then automatically add a -
Any help is greatly appreciated. Thanks
I suggest you to follow that process:
If the current input's value is not corresponding to the (XXX) XXX-XXXX format, checks the number of digits only.
If more or exactly 6 (= XXXXXX...), converts to (XXX) XXX- plus the rest if present.
Else if bewteen 3 and 6 (= XXX...), converts to (XXX) plus the rest if present (note the last space in the format I wrote).
Then updates the input's value.
Else if the displayed format is right, just avoid the possibility to type more characters.
The code snippet below (with some bonuses):
$('#telephone').on('keyup', function(e) {
// If not removing a character...
// (Without that check, you'll not be able to remove characters correctly.)
if (e.key !== 'Backspace') {
let value = $(this).val();
// If the value is not corresponding to wanted format...
if (!/\(\d{3}\) \d{3}-\d{4}/.test(value)) {
// Only keeps digits.
value = value.replace(/[^\d]/g, '');
// If we have at least 6 digits, converts the value to "(XXX) XXX-...".
if (value.length >= 6) {
value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`;
}
// If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...".
else if (value.length >= 3) {
value = `(${value.substring(0, 3)}) ${value.substring(3)}`;
}
// Updates the input's value.
$(this).val(value);
}
// If the format is correct, just avoid to have too much characters.
else {
$(this).val(value.substring(0, 14));
}
}
});
// Doesn't display unwanted characters.
// (Did this on a different event. Try replacing "input" by "keyup" to see why.)
$('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\d() -]/g, ''));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="telephone">
Try something like this after the 6th character?
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="phone" maxlength="14" />

Strict number input field

I have a simple input field with type set to number. This will be used to enter input in [0,255] range (for RGB).
<input type="number" id="inputBox" min="0" max="255" step="1" />
In its current form, this input field will accept the following values:
012 // zero prefixed numbers
1.0 // floating-point
.1 // floating-point
-5 // range underflow
300 // range overflow
I want it to accept only the integers in the range of [0,255]. So, no zero prefix, no floating-point numbers.
I've solved the range problem using input event:
inputBox.addEventListener("input", function () {
if (this.validity.rangeUnderflow) {
this.value = this.min;
}
else if (this.validity.rangeOverflow) {
this.value = this.max;
}
});
and floating-point problem using keydown event (by not allowing .):
inputBox.addEventListener("keydown", function (e) {
if (!isFloat(this.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
});
function isFloat(f) {
var f = parseFloat(f);
var floor = Math.floor(f);
var fraction = f - floor;
if (fraction > 0) {
return true;
}
return false;
}
I'm stuck at solving the zero prefixed numbers problem. I can use the following line of code in the input event to remove zero prefix
this.value = this.valueAsNumber; // or parseInt(this.value, 10)
which is working fine, but this kind of breaks the input field's functionality. I can't enter values with E notation. In my case, I don't need to, but I might somewhere else. As soon as I enter 1e, it evaluates to NaN, and is assigned back to input field.
Is there a way to make these both work?
JSFiddle
I just worked on a problem like this. It's super easy to do:
inputBox.addEventListener("keydown", function (e) {
if (!isFloat(this.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
while ( this.value.toString()[0] === "0" && this.value.length > 0){
this.value = this.value.toString().slice(1);
}
});
Note that the value of the field might change in ways other than keydown events, suck as paste. So I would put these checks in a function, validationCheck, and run that function for each relevant event, including the catchall- onchange.
You can use a regular expression such as:
<input type="text" pattern="0|[1-9]\d*">
this will gives you a string representation of a positive whole number without prefixed zeros.
You then have to test with JavaScript if the value is less than or equals 255.
Here is a JSFiddle.
String with only multiple zeros are not accepted.

Categories

Resources