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.
Related
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.
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.
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;"
So I have this function:
function inputCheck()
{
var check = document.forms["drinkList"]["quant1"].value
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
I am using this code to check if the user has entered a character into a textbox. If they did, then it will display an alert saying that it only accepts numbers.
Thing is, I have 11 more text boxes I have to run this function under.
Is there anyway I can get this to work, without recreating 11 more functions?
The other textbox names are:
quant2,
quant3,
quant4,
quant5,
whip,
cream,
sugar,
chocolate,
caramel2,
NOTE: I am also using onchange to make it a live check.
Sorry, didn't read clearly earlier. This should do, I guess.
<input onchange="inputCheck(this)">
function inputCheck(elem){
var check = elem.value;
if (isNaN(check))
{
window.alert("Input numbers only");
return false;
}
}
A more efficient way to hook an event to multiple inputs is to hook an event to a parent (like, say, <body>), and check the target of the events bubbling up:
var names = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
document.body.addEventListener('keyup', function (e) {
// skip event if it was NOT triggered on a matching element
if (names.indexOf(e.target.name) === -1) { return; }
// code to process event...
});
As asides:
Use <input type="number">. This is a facility provided by the browser, it will work immediately at input-time, among other niceties (like providing a number-only keypad on mobile devices instead of a full keyboard). Here's documentation and browser support for further reading.
I recommend checking the built-in feature input type=number
However, if you really want to check it for yourself you could do something like:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function numberOnly() {
var value = this.value;
if (!isNumber(value)) {
console.dir('not a number!'); // replace this with your ALERT
this.classList.add('error');
} else {
this.classList.remove('error');
}
}
var inputs = document.querySelectorAll('.number-only'); // selects all the inputs that have the class .number-only
[].forEach.call(inputs, function(input) {
input.addEventListener('keyup', numberOnly); // validate the input using the numberOnly onkeyup
});
input {
display: block;
margin: 5px;
border: 1px solid #aaa;
padding: 5px 10px;
}
input.error {
outline-color: #f00;
border: 1px solid #f00;
position: relative;
}
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
<input type="text" class="number-only">
why don't use jquery,it can select all textbox if add same class, example:nonNumberTextbox.
$("#drinkList .nonNumberTextbox").each(function(index, node) {
if (isNaN(node.value)) {
window.alert("Input numbers only");
return false;
}
});
In your code isNaN(check) will always return false. This is because the .value property of an input element always returns a string and isNaN of a string is false.
You need to coerce check to a number before passing it to isNaN. I would suggest using the unary operator +. You also need to make sure that check is not empty or an all white-space string because the unary plus will those will coerced them to 0.
if (check.trim() === '' || isNaN(+check)) {
Alternatively depending on your needs you could use parseInt or parseFloat which will return NaN when parsing an empty or all white-space string.
if (isNaN(parseInt(check, 10))) { // if only integers are allowed
}
if (isNaN(parseFloat(check))) { // if integers and decimals are allowed
}
Yet another alternative would be to use a regular expression to validate the string without coercion.
if(!/^\d+$/.test(check)) { // if the number needs to be an integer
}
if(!/^\d+(?:\.\d*)?$/.test(check)) { // if the number can be an integer or a decimal
}
Try if this works
var textboxes = ['quant2', 'quant3', 'quant4', 'quant5', 'whip', 'cream', 'sugar', 'chocolate', 'caramel2'];
for (var i = 0; i < textboxes.length; i++ ){
var check = document.forms["drinkList"][textboxes[i]].value;
if (isNaN(check)){
window.alert("Input numbers only");
break;
}
}
Hello I have try a lot but can't solve . can any one explain me how I'll drive a JavaScript event after write" in " . I mean i wanted to make a div display:none to display:block after write " in ". that's a auto suggestion issue i've attaching a image the pattern is like that [word] [in] [word].
That's will do onkeyup event.
JS version...
var myInput = document.getElementById('myInput');
var messageBox = document.getElementById('messageBox')
myInput.addEventListener("keyup", checkString);
function checkString() {
var str = myInput.value;
// notice whitespace either side of "in" to prevent false positives
if (str.indexOf(' in ') > -1) {
messageBox.style.display = "block";
} else {
messageBox.style.display = "none";
}
}
#messageBox {
display: none;
padding: 15px;
background: #f2f2f2;
border: 1px solid #e6e6e6;
margin-top: 15px;
}
<input id="myInput" placeholder="Type here">
<div id="messageBox">In was typed</div>
Use input event in jQuery
$('#some_text_box').on('input', function() {
var value = $(this).val();
// do your stuff
// split the value by space and check if it contains 'in'
});
Using jQuery keyup event you can get value which user type in text box while user typing. Then with the use of indexOf javascript method you can compare string with in word. if match found you can display div otherwise hide that div.
Make sure to use toLowerCase() to convert string enter by user in lower case to get perfect match with in word. if user enter in in uppercase it function works fine.
DEMO
What is indexOf() method ?
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.
$('#text').on('keyup', function() {
var value = $(this).val();
if(value.toLowerCase().indexOf(' in ') >= 0){
$('yourdiveselector').show()
}else{
$('yourdiveselector').hide()
}
});