html numeric input allow 6 digits only - html

I have a input. I want only numeric values.
And I want there to be six numbers only.
How do i do it?
I have:
<input type="number" placeholder="YYMMDD" id="myKadA" maxlength="6" style="width:90px !important" onchange="checkMyKad()" size="8" class="form-control block-centered ic-input" required>
There is a css to remove the scroll bar from the input boxes.
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: textfield;
}
Previously it was input type="text" and maxlength="6" limited it to six chars long. How do i now specify a number 6 digit only

JAVASCRIPT WAY
HTML
<input type="number" placeholder="YYMMDD" id="myKadA" onkeydown="limit(this, 6);" onkeyup="limit(this, 6);" onkeyup="this.value = minmax(this.value, 0, 6)" required>
JS
function limit(element, max_chars)
{
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return 0;
else if(parseInt(value) > max)
return 100;
else return value;
}
HTML WAY
<input type="number" placeholder="YYMMDD" id="myKadA" maxlength="6" min="0" max="6" required>
JQUERY WAY
<input type="number" placeholder="YYMMDD" id="myKadA" min="0" max="6" required>
var max_chars = 6;
$('#myKadA').keydown( function(e){
if ($(this).val().length >= max_chars) {
$(this).val($(this).val().substr(0, max_chars));
}
});
$("#myKadA").change(function() {
var max = parseInt($(this).attr('max'));
var min = parseInt($(this).attr('min'));
if ($(this).val() > max)
{
$(this).val(max);
}
else if ($(this).val() < min)
{
$(this).val(min);
}
});

Use the attribute max and min for input type number

Try
<input type="number" onKeyPress="if(this.value.length==6) return false;"/>
or else you can change the input type to "month"
<input type="month" min="2018-03" value="2018-05">
Hope this works.

this looks like a promising answer to your case.

As you have mention in placeholder -YYMMDD
I would suggest you to use input type="date"

Max length will not work with .
You have to make use of jQuery/Javascript.
Below is a working snippet.
HTML:
<form>
<label for="myKadA" class="control-label">Number:</label>
<input type="number" id="myKadA" data-max="6" class="form-control" required>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
jQuery:
<script>
$(document).ready(function () {
$(".btn-primary").click(function (e) {
e.preventDefault();
var keyObj = $("#myKadA");
var maxLength = parseInt(keyObj.attr('data-max'));
if((keyObj).val().length !== maxLength){
alert("You must enter exactly " + maxLength + " digits");
}
});
})
</script>

Since maxlength attribute is ignored with <input type"number"/> as explained here.
You could try adding some validation with javascript using something like:
HTML
<input onKeyDown="validateNum(event, this)" type="text" maxlength="6" max="6" min="6" placeholder="YYMMDD" id="myKadA" style="width:90px !important" onchange="checkMyKad()" class="form-control block-centered ic-input" required>
Javascript
function validateNum(event, input) {
event.preventDefault();
var currVal = input.value ? input.value : "";
// Checks if the key pressed is a number and the right length
if(!isNaN(event.key) && currVal.length < 6){
input.value = currVal + event.key;
}
// Backspace functionality
else if(event.keyCode == 8 && currVal > 0) {
input.value = input.value.slice(0, -1);
}
}

Try to write maxlength=6 without quotes. I tried it in react js like this way: maxLength={6}; and it helped me.

If you want only numbers in input field,
<input type="number" max="6"/>
so it renders into input type number field which allows only 6 digits

Related

Which input element that accept digits only and allows a limited number of characters

I am trying to implement an (zip code of my country) input field that only accept digits and limit the number of characters to 5.
Which html input type and attributes are more appropriate for this task ?
<input type="text" name="zipcode" pattern="[0-9]{5}" />
pattern="\d{5}" would also work. But make sure to re-check it in your target-script because form-elements can be manipulated.
A complete example (WITH JQUERY) for checking values on change or keyup in the .checkFieldNum values and on submit the form.
JS
function checkNum(value)
{
return value.match(/\d{5}/);
}
$(document).ready(function(){
// trigger if element-value with class="checkFieldNum" changes or key is pressed
$('.checkFieldNum').on('change keyup',function(event){
if(checkNum($(this).val()) === false)
{
$(this).css({background:'tomato'})
}
else
{
$(this).css({background:''})
}
})
// trigger if form should be submitted
$('.formClassForSubmit').on('submit',function(event){
event.preventDefault();
var goOn = true;
$('.checkFieldNum').each(function(){
if(checkNum($(this).val()) === false)
{
goOn = false;
alert($(this).attr('name') + ' has wrong value')
}
})
if(goOn === true)
{
// In this case, everything is OK and go on whatever you will do..
}
})
})
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="?" method="post" class="formClassForSubmit">
<input type="text" class="checkFieldNum" name="zipcode1" pattern="[0-9]{5}" />
<input type="text" class="checkFieldNum" name="zipcode2" pattern="\d{5}" />
<input type="submit" name="send" value="send" />
</form>
see https://jsfiddle.net/7hbj6a3e/3/
<input type="number" minlength="5" maxlength="5" name="zipcode" />
see https://www.w3schools.com/tags/tag_input.asp

Trigger html5 validation without form post

I want to achieve something like this without form post, as it will redirect the page.
here is my code
<form>
<input type="number" step="any" min="0" required oninvalid="this.setCustomValidity('Please enter price with decimal format, eg x.xx .')">
<button type="submit">submit</button>
</form>
I've did some research it seems like it has to be triggered with form post. Possible to trigger the html5 validtion with jquery function button click ?
Set a custom validation message on input change and intercept the form submit event:
var form = document.querySelector('form'),
input = document.querySelector('#input-price');
input.addEventListener("change", function (event) {
if (!input.checkValidity() || !/^\d+(\.\d+)?$/.test(input.value)) {
input.setCustomValidity("Please enter price with decimal format, eg x.xx .");
} else {
input.setCustomValidity("");
}
});
form.addEventListener("submit", function (event) {
event.preventDefault();
});
<form>
<input id="input-price" type="number" step="any" min="0" required>
<input type="submit">
</form>
input.checkValidity() returns true when the input value is a number as in 2, .1 and 1e10. The regex test then filters the two last cases (.1 and 1e10) out.
the html5 “pattern” attribute doesn't work in all Browsers
the only way is to use JavaScript code
try this code
Html
<input id="amount" maxlength="7" type="text" />
javaScript
$("#amount").on("keyup", function(){
var valid = /^\d{0,4}(\.\d{0,3})?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 1);
}
});
to avoid accepting invalid input when pasting text (idea of #le_m)
try this second solution :
html
<input id="amount" maxlength="7" type="text" />
JS
$("#amount").on("change paste keyup", function(){
var valid = /^\d*(\.\d*)?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 7);
}
});
result :
http://jsfiddle.net/vY39r/866/

Prevent negative inputs in form input type="number"?

I want to restrict user input to positive numbers in an html form.
I know you can set min="0", however it is possible to bypass this by manually entering a negative number.
Is there any other way to solve this without writing a validation function?
This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.valid property. This will be true if and only if the input falls within the range.
<html>
<body>
<form action="#">
<input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is not possible without validating the value of the input.
input type=number
The input element with a type attribute whose value is "number" represents a precise control for setting the element’s value to a string representing a number.
Since it is a string representing the number there is no way to be sure that string may be representing numeric values or not.
The Permitted attributes will not give you the ability to validate the value of the number input control.
One way to do this with the help of JavaScript could look like this.
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function(){
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
<input type="number" min="0" />
If you are planing on sending your data to a server make sure to validate the data on the server as well.
Client side JavaScript can not ensure that the data that is being sent will be what you expect it to be.
If you want to ensure default value, i.e min value, or any other value, this is working solution. This is also preventing to clear the input field. Same way you can set to it's max value as well.
<input type="number" min="1" max="9999" maxlength="4" oninput="this.value=this.value.slice(0,this.maxLength||1/1);this.value=(this.value < 1) ? (1/1) : this.value;">
The following script will only allow numbers or a backspace to be entered into the input.
var number = document.getElementById('number');
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<input type="number" id="number" min="0">
type="number" already solves allowing numbers only to be typed as the other answers here point out.
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!
On html put onKeypress event listener
<input type="text" onkeypress="validate(event)">
write the validate function like this:
<script>
function validate(event) {
if (event.key == "-") {
event.preventDefault();
return false;
}
}
</script>
in case of angularjs pass $event in place of event, i have tested this in angularjs and in javascript
WAY 01:
Template:
<input name="price" type="number" (keydown)="onKeydown($event)" min="0" required />
file-name.ts:
onKeydown(event: KeyboardEvent): boolean {
if (!((event.keyCode > 95 && event.keyCode < 106)
|| (event.keyCode > 47 && event.keyCode < 58)
|| event.keyCode === 8)) {
return false;
}
return true;
}
WAY 02:
Template:
<input name="price" type="number" min="0" oninput="this.value = Math.abs(this.value)" required />
In HTML5, I like this way. Also it's much suitable with angular.
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Angular | Typescript Syntax
HTML:
<input type="number" (keydown)="onKeyDown($event)">
ts File:
onKeyDown(e:any):void{
if(!e)
return;
console.log('ee',e);
if((e.code==='Minus' && e.keyCode==189 && e.key==='-') || (e.keyCode==187 && e.key==='+')
||(e.code==='KeyE' && e.keyCode==69 && e.key==='e')){
e.preventDefault();
}
}
JavaScript Syntax
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>Create Account</h1>
<form id="user" name="user">
<div class="row">
<div class="col-6">
<label for="fname">First Name*</label>
<input type="number" id="fname" placeholder="Enter Your first name" required>
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$('#fname').keydown(function(e){
console.log('evt e.key:::::', e);
if(e.key=='-' && e.keyCode==189 || e.key=='+' && e.keyCode==187 )
{
e.preventDefault();
}
console.log('evt e.keyCode:::::', e.keyCode);
console.log('evt e.code:::::', e.code);
});
</script>

HTML5 required attribute one of two fields

I have a form with two required input fields:
<form>
<input type="tel" name="telephone" required>
<input type="tel" name="mobile" required>
<input type="submit" value="Submit">
</form>
Is it possible to get browsers to validate so only one of them is required? i.e if telephone is filled, don't throw an error about mobile being empty and vice versa
Update 2020-06-21 (ES6):
Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:
document.addEventListener('DOMContentLoaded', function() {
const inputs = Array.from(
document.querySelectorAll('input[name=telephone], input[name=mobile]')
);
const inputListener = e => {
inputs
.filter(i => i !== e.target)
.forEach(i => (i.required = !e.target.value.length));
};
inputs.forEach(i => i.addEventListener('input', inputListener));
});
<form method="post">
Telephone:
<input type="tel" name="telephone" value="" required>
<br>Mobile:
<input type="tel" name="mobile" value="" required>
<br>
<input type="submit" value="Submit">
</form>
This uses the input event on both inputs, and when one is not empty it sets the required property of the other input to false.
Original Answer (jQuery):
I played around with some ideas and now have a working solution for this problem using jQuery:
jQuery(function ($) {
var $inputs = $('input[name=telephone],input[name=mobile]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
});
});
I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.
Based on Andy's answer, but I needed a checkbox implementation & came up with this.
what role(s) do you want?
<input type="checkbox" data-manyselect="roler" name="author" required>
<input type="checkbox" data-manyselect="roler" name="coder" required>
<input type="checkbox" data-manyselect="roler" name="teacher" required>
where will you work?
<input type="checkbox" data-manyselect="placement" name="library" required>
<input type="checkbox" data-manyselect="placement" name="home" required>
<input type="checkbox" data-manyselect="placement" name="office" required>
jQuery(function ($) {
// get anything with the data-manyselect
// you don't even have to name your group if only one group
var $group = $("[data-manyselect]");
$group.on('input', function () {
var group = $(this).data('manyselect');
// set required property of other inputs in group to false
var allInGroup = $('*[data-manyselect="'+group+'"]');
// Set the required property of the other input to false if this input is not empty.
var oneSet = true;
$(allInGroup).each(function(){
if ($(this).prop('checked'))
oneSet = false;
});
$(allInGroup).prop('required', oneSet)
});
});
Here for anyone else getting here by googling and wanting a quick solution for one of many checkboxes.
You would better do form data validation with Javascript anyway, because the HTML5 validation doesn't work in older browsers. Here is how:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation Phone Number</title>
</head>
<body>
<form name="myForm" action="data_handler.php">
<input type="tel" name="telephone">
<input type="tel" name="mobile">
<input type="button" value="Submit" onclick="validateAndSend()">
</form>
<script>
function validateAndSend() {
if (myForm.telephone.value == '' && myForm.mobile.value == '') {
alert('You have to enter at least one phone number.');
return false;
}
else {
myForm.submit();
}
}
</script>
</body>
</html>
.
Live demo here: http://codepen.io/anon/pen/LCpue?editors=100. Let me know if this works for you, if you will.
For two text fields #Andy's answer is working awesome, but in case of more than two fields we can use something like this.
jQuery(function ($) {
var $inputs = $('input[name=phone],input[name=mobile],input[name=email]');
$inputs.on('input', function () {
var total = $('input[name=phone]').val().length + $('input[name=mobile]').val().length + $('input[name=email]').val().length;
$inputs.not(this).prop('required', !total);
});
});

Limit number of characters allowed in form input text field

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?
Below is the input field as part of my form:
<input type="text" id="sessionNo" name="sessionNum" />
Is it using something like maxSize or something like that?
maxlength:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field
will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />
Add the following to the header:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);"
onKeyUp="limitText(this,5);"" />
Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.
According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.
Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway
<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.
Maxlength
The maximum number of characters that will be accepted as input.
The maxlength attribute specifies the maximum number of characters allowed in the element.
Maxlength W3 schools
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>
I always do it like this:
$(document).ready(function() {
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
maxChars.on('keyup', function(e) {
length = new Number(maxChars.val().length);
counter = max_length - length;
$("#sessionNum_counter").text(counter);
});
}
});
Input:
<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>
You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9"> for numbers
or
<input type = "email" maxlength="9"> for email
validation will show up
<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">
function maxLengthCheck(object) {
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
The following code includes a counted...
var count = 1;
do {
function count_down(obj, count){
let element = document.getElementById('count'+ count);
element.innerHTML = 80 - obj.value.length;
if(80 - obj.value.length < 5){
element.style.color = "firebrick";
}else{
element.style.color = "#333";
}
}
count++;
} while (count < 20);
.text-input {
padding: 8px 16px;
width: 50%;
margin-bottom: 5px;
margin-top: 10px;
font-size: 20px;
font-weight: 700;
font-family: Raleway;
border: 1px solid dodgerblue;
}
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80" class="text-input" name="bikeTitle" ></p>
<span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:
Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.
Just Numbers:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);
Just Letters:
oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"
Full example:
<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>
Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>