validate input with a number range with on keypress event Jquery - javascript

I have the following situation.I have an input and I need that as I write I validate that the value of that input is between 1 and 100. The function cannot allow to write a number greater than 100. In my code I get that validation done but it only works when I write the fourth character, then it does not let me write anything else, I need that if I have 2 characters in the input, I will not be allowed to write a third because the number would be greater than 100, I should only write a third character if the written numbers are 1 and 0, that is 10.
<input type="text" class="porciento" name="">
$(document.body).on("keypress", ".porciento", function (event) {
var numero=$(this).val();
if($(this).val()>100){
event.preventDefault();
}
});

$(document.body).on("keypress", ".porciento", function (event) {
var numero=$(this).val();
if($(this).val()>100){
event.preventDefault();
}
});
<input type="text" class="porciento" name="">

Here you go... you may personalize it as you want, but this is the logic.
document.getElementsByTagName('input')[0].addEventListener('keydown', (e) => {
const val = parseInt(e.target.value + e.key);
if (!isNaN(val) && val > 100) {
e.preventDefault();
}
}, {passive: false, capture: true});
<input type="text" name="myInput">

Two important factors to consider when performing range number validation during keypress;
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 100 is selected, pressing 9 will not turn into 1009 but 9 instead.
You can checkout my answer here for further explanation and change a little bit of the code to suit your need.

Related

how can I count number of digits with leading zeros in javascript?

I have a form where a user enters a number, say an employee ID number or something like that. The field is set to reject anything that's not a number, so they can't just put in "bob" or faceroll the keyboard or whatever. Otherwise I'd convert this to a string.
I need to further validate and make this form reject anything that doesn't match the correct number of digits, lets say 5. It also needs to count leading zeros. For example - let's assume an Employee ID of 01234, which should match 5 digits. Currently, I'm losing that leading zero and it's rejecting values like the example above.
So, how can I:
count the number of digits in this number,
preserve leading zeros,
make sure they user is obligated to enter a number, with a JavaScript formula?
You should go with your original idea and use a string for such a field.
You can check whether the string is a number with a simple regex such as
let regex = /^[0-9]*$/;
regex.test(string);
It should return true if the string contains only digits.
If you get the input element's value with element.value it will return a string that preserves leading zeroes.
Limiting the input field's characters is covered in HTML text input allow only numeric input
I've copied and modified the example below to show an input field that only accepts up to 8 numbers and will log the ID on submit.
// Restricts input for the given textbox to the given inputFilter.
// Source: https://stackoverflow.com/a/469362
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
});
}
const inputField = document.getElementById("employee-id");
const submitButton = document.getElementById("submit");
setInputFilter(inputField, function(value) {
return /^\d*$/.test(value) && (value.length <= 8);;
});
submitButton.addEventListener('click', event => {
console.log(inputField.value)
})
User ID: <input id="employee-id">
<button id="submit">submit</button>
Try this.
<input id="number" type="text" minlength="5" maxlength="5" value="42" pattern="\d{5}">
Check validity via JS
document.querySelector('#number').checkValidity()
check validity via CSS
input {
outline: none;
border: 1px solid green;
}
input:invalid {
border: 1px solid red;
}
if you need further validation just use javascript to validate it.

Allow only two types of characters to be inserted into an input field

I have a text field where I need only 1 and 0 anything else will break my logic code.
How do i possibly restrict any other character from being entered in an input field?
I looked through posts regarding on a somewhat similar subject but they allowed numbers from 0-9 and so on.
I tried using the pattern attribute in html but there is no pattern that does this, at least i haven't found it.
I have found this code:
$(function(){
$('#BinaryInputArea').bind('input', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
});
which restricts SPACES from being entered, this uses again patterns that only seem to be known by veterans. I tried adding [2-9] in the .replace section but sadly it was out of the bounds of my logic.
EDIT: I am using a TextArea for input so a regular input pattern:[0-1]
wont work
You can do this with regular expressions:
var txtInput = document.getElementById("txtInput");
txtInput.addEventListener("keydown", function(evt){
var regEx = /^(0|1)$/;
// Account for two ways to press 0 and 1 on full-size keyboards
var key1 = String.fromCharCode(evt.keyCode);
var key2 = String.fromCharCode(evt.keyCode-48); // Adjustment for the keydown event
// Test key against regular expression
if(!regEx.test(key1) && !regEx.test(key2)){
evt.preventDefault();
}
});
<form>
<textarea id="txtInput"></textarea>
<button>Submit</button>
</form>
Or, you can do this by checking for specific keys being pressed:
var input = document.getElementById("txtInput");
// Do event binding in JavaScript, not in HTML
input.addEventListener("keydown", function(evt){
// Get the code for the key that was pressed
var char = evt.keyCode;
// Is the SHIFT key being held down?
if(evt.shiftKey){
// If so, cancel the event
evt.preventDefault();
} else {
// Not the SHIFT key, but if it is 48, 49, 96, 97
// (the four ways to get 0 or 1 on a keyboard with a num pad)
switch (char) {
case 48:
case 49:
case 96:
case 97:
break; // do nothing
default:
// Some other key, cancel the event.
evt.preventDefault();
break;
}
}
});
// Don't allow pasting into the field
input.addEventListener("paste", function(evt){
evt.preventDefault();
});
<form>
<textarea id="txtInput"></textarea>
<button>Submit</button>
</form>
If you want to do it using javascript you can do something like:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 49'>
</input>
EDIT: Ok, my first post just pretended to give an example of how it could be done on a line. But you need to have into account a lot of details like allowing the user to use the keyboard keys, copy and paste events, delete characters, etc. You should also control if the user paste a non-valid value.
So here is a more detailed example:
In one line:
<input name="number" onkeyup="if (/[^0-1]|^0+(?!$)/g.test(this.value)) this.value = this.value.replace(/[^0-1]|^0+(?!$)/g,'')">
A jquery example:
$(document).ready(function() {
$('input.validateBinary').keyup(function(event) {
var regEx = /^(0|1)$/;
if (!regEx.test(this.value)) {
this.value = this.value.replace(/[^0-1]|^0+(?!$)/g, '');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="validateBinary" />

Html input field set maximum value [duplicate]

This question already has answers here:
How to prevent inserting value that is greater than to max in number field in html
(2 answers)
Closed 5 years ago.
the max property does not work if i put a number in the field. Why?
it works only when i change the value with the arrows.
JS Fiddle
HTML
<input id= "0" class='labelmax form-control'
type='number' name='max_label' min='0' max='99' value='1'>
With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (parseInt($(this).val()) <= 99 && parseInt($(this).val()) >= 0)
;
else
$(this).val($(this).data("old"));
});
});
For it work automatically you have to wrap your input within a form and add a submit button to that form
If you don't want to wrap it in a form and want maximum customisation you'll have to use Javascript and setup an event handler that will listen for user input and act accordingly
You can use something like below by making use of simple JavaScript. In your code I dont see any JS.
document.getElementsByClassName('labelmax form-control')[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input id= "0" class='labelmax form-control' type='number' name='max_label' max='99' value='1'/>

jQuery .val() ignoring trailing decimal points

I am currently working on limiting the allowed input in a numeric text field. I check the length of the value of the input field, if it is >= to the maxlength attribute, don't input anything.
$('input[maxlength]').on('keyup', '', null, function(event) {
var ref = $(this),
val = ref.val();
if ( val.length >= this.maxLength && event.which != 8){
return false;
}
}
However, if the currently value of the field ends in a decimal (eg "4."), then the val() method returns "4", which throws off the whole process. How can I read the contents of the input field while including the trailing decimal points?
http://jsfiddle.net/n3fmw1mw/329/ (Type in '4.' and you'll see what I'm talking about.)
EDIT: I've tried something from Mr. Hill's suggestion and now I have this
$('input[maxlength]').on('keydown', '', null, function(event) { //enforce maxlength on all inputs, not just text inputs
var ref = $(this);
ref.attr('type','text');
var val = ref.val();
if ( val.length >= this.maxLength && event.which != 8){
ref.attr('type','number');
return false;
}
ref.attr('type','number');
});
But now nothing is being inserted into my text box, even if debugging and seeing that we aren't returning false.
The decimal is being dropped because your input type is number. Set your input type to text.
<input type="text" id="textbox1"/>
Here's a working fiddle.
EDIT
Based on your new requirement of not being able to change the source, the code below should get you pointed in the right direction.
jQuery does not allow you to change the type of an element. To do it, you must remove the element and add one of the correct type in its place. The code below does just that.
Note: In an effort to make the code more reusable, I added a class to your element and then edited all elements with that particular class.
// Add class to identify that element type needs changed
$("#textbox1").addClass("numberToText");
// Swap number type input with text
$('.numberToText').each(function() {
$("<input type='text' />").attr({
id: this.id,
name: this.name,
value: this.value
}).insertBefore(this);
}).remove();
$("#textbox1").keyup(function() {
$('#log').append("Value: " + $('#textbox1').val() + '<br/>');
});
$(".button").click(function() {
$('#log').append("Value: " + $('#textbox1').val());
})
Here's a working fiddle.

HTML5 : Input field with the type of 'number' will still accept higher value than its 'max' using keyboard inputs

Hello guys need some help here. i want to have limit the numbers inputted in my input field by putting max attribute to it. i have no problem with that until i use my keyboard to input data on it. seems like the max attribute is not filtering the input coming from the keyboard.
e.g
<input type="number" max="5" />
i can't go until 6 using the up and down arrow but when i manually put 6 using keyboard it's accepts it. how can i prevent? thank you
You would need to use JavaScript to do it. This will not let the user enter a number higher than 5:
<input type="number" max="5" onkeyup="if(this.value > 5) this.value = null;">
Another possible solution is to completely block the keyboard input by replacing onkeyup=".." event in the code above with onkeydown="return false".
have no problem with that until i use my keyboard to input data on it.
seems like the max attribute is not filtering the input coming from
the keyboard
This is how HTML5 validation/constraint work. However, it will invalidate when the form submits. Alternatively, you can validate it yourself. To validate yourself, you need to wire up Javascript and call the checkValidity() on the input element.
checkValidity() of the constraints API will check the validity state of the element and will return the state of whether the input element validate or not. This will also set the validity object on the input so that you can query more details.
Ref: https://html.spec.whatwg.org/multipage/forms.html#constraints and https://html.spec.whatwg.org/multipage/forms.html#form-submission-algorithm
You can also use the :invalid selector in CSS to highlight invalid inputs.
Example Snippet:
var input = document.getElementById('test'),
result = document.getElementById('result');
input.addEventListener('blur', validate);
function validate(e) {
var isValid = e.target.checkValidity();
result.textContent = 'isValid = ' + isValid;
if (! isValid) {
console.log(e.target.validity);
}
}
input[type=number]:invalid {
border: 2px solid red;
outline: none;
}
<label>Enter value and press tab: </label><br/>
<input id="test" type="number" min="1" max="10" />
<hr/>
<p id="result"></p>
You can use javascript to restrict the maximum input value to 5.
HTML
using oninput as a event handler
<input type="number" max="5" oninput="checkLength(this)" />
JS
function checkLength(elem) {
// checking if iput value is more than 5
if (elem.value > 5) {
alert('Max value is 5')
elem.value = ''; // emptying the input box
}
}
DEMO
An Utility Function to Solve Two Problem
Problem 1: Limit user input to maximum n digit
For this use n number of 9 as max parameter. As an example if you want to limit user input in 4 digit then max param value will be 9999.
Problem 2: Limit user input at a maximum value
This is intuitive. As an example If you want restrict the user input to maximum 100 then max param value will be 100.
function getMaxInteger(value, max) {
if(!value) return;
if( parseInt(value) <= max ) {
return value;
}
return getMaxInteger(value?.substr(0, value?.length-1), max);
}
function maxInt(value, max) {
return getMaxInteger(value?.replace(/\D/,''), max);
}
Use this maxInt method on input change handler
ngModelChange for Angular
onChange for React
v-on:change or watch for Vue
onkeyup="if(this.value > <?=$remaining?>) this.value = null; else if(this.value < 1) this.value = null;"

Categories