Allow digits to be replaced in a length-limited field - javascript

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" />

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>

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" />

How to allow only numbers and format value in javascript

I would like to know how to validate the text field that allows only numbers and then format the value in javascript.
How to validate the input text by not allowing to paste,ctrl,shift, backspace and del and not allowing special charaters and alphabets,
<input name="samount" type="text" id="samount" class="form-control"
#keyup=${this.formatCurrency}>
formatCurrency(e){
var myinput = e.target.value;
var val = myinput;
val = val.replace(/[^0-9]/g,'');
if(val != "") {
var valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
e.target.value = val;
this.rateValue();
}
Should allow only numbers
Keyup event contains the key typed, make a test on it (if parseInt or dot ...).
*try to update your regex expression and use match function in the if condition to check whether your field values are matching with the regrex.
* every key has it seperate keycode u can validate using that keycode to mention that this key doesn't work on this text field
Easiest way is to delete the input value on keyup when it is not numeric.
$("#myinput").keyup(function(e) {
if($(this).val().match(/^[0-9]+$/))
return;
else
$(this).val('');
});
Alternatively check for e.keyCode and prevent input when it does not match the ranges 48-57 and 96-105(numpad has separate keycodes)

Field to accept only 5 integers & 2 decimals

I want to add a restriction to the weight field to accept only 5 integers & 2 decimals. I have tried below regex but facing issue with the same.
/^(\d{1,5})(\.\d{1,2})?$/
Field should not accept 6th integer.
Code:
Enter weight:
<input type="text" id="weight" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("weight").value;
var regexp = /^(\d{1,5})(.\d{1,2})?$/g;
var result = x.match(regexp);
alert(result);
}
</script>
You can try something like this:
Explanation:
Keep a variable previousValue to hold last correct value. By default, it will be blank.
Validate input value. If value is incorrect, stop event and set previousValue as input's value.
On valid input, set current value as previous value.
Validation conditions:
Input must have numbers(0-9) and Decimal(.);
Integer part can have max of 5 numbers
Decimal part can have max of 2 numbers
var previousValue = "";
function myFunction(event) {
this.value = this.value || "";
if(validateInput(this.value)){
event.preventDefault();
this.value = previousValue;
}
else{
previousValue = this.value
}
}
function validateInput(value){
var regex = /^[0-9.]*$/;
var valid = regex.test(value);
var parts = value.split(".");
return ( !valid ||
parts.length > 2 ||
parts[0].length > 5 ||
(parts[1] && parts[1].length > 2)
)
}
function registerEvents(){
document.getElementById('weight').addEventListener('keyup', myFunction)
}
registerEvents();
Enter weight:
<input type="tel" id="weight" maxlength="8">
Pointers:
If you have defined max possible length, use maxlength on input to restrict users.
Its better to attach event using addEventListener than adding it in HTML.
Its also better to separate validation and processing logic. Keeps you code clean and maintainable.
Instead of using type="text", use type="tel". This is a minor optimisation for mobiles. It will open number keyboard instead.

Categories

Resources