HTML maxlength attribute not working on chrome and safari? - html

<input type="number" maxlength="5" class="search-form-input" name="techforge_apartmentbundle_searchformtype[radius]" id="techforge_apartmentbundle_searchformtype_radius">
This is my HTML, taken with firebug (on chrome).
I am allowed to write as much as characters as I want in the form field - in Chrome and Safari.
When on Firefox or IE10, the limit is fine.
I haven't found this issue around on the net.
Note: type="number" - not text.
Anyone saw this issue before?

Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>

Use the max attribute for inputs of type="number". It will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max and a min value you can specify the range of allowed values:
<input type="number" min="1" max="999" />
See this example
EDIT
If, for user experience, you would prefer the user not to be able to enter more than a certain number, use Javascript/jQuery, as seen in this example

The maxlength attribute does not apply to an input of type="number"
From W3 HTML5 spec concerning type="number"
The following content attributes must not be specified and do not
apply to the element: accept, alt, checked, dirname, formaction,
formenctype, formmethod, formnovalidate, formtarget, height,
maxlength, multiple, pattern, size, src, and width.
Source: http://dev.w3.org/html5/spec/Overview.html#number-state-type-number
(under Bookkeeping details)
In FF and IE, the input is falling back to be a text input and therefore, maxlength applies to the input. Once FF and IE implement type="number", they should also implement it in a way where maxlength does not apply.

For those who still can't get it to work... Try this to fire up the fatter number pads:
<input type="number" name="no1" maxlength="1" size="1" max="9" pattern="[0-9]*" />
And the js:
$('input[name="no1"]').keypress(function() {
if (this.value.length >= 1) {
return false;
}
});

Here is an example using type="number" and maxlength, that works with Chrome, IE and others. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function test(id, event) {
var element = $("#" + id);
var len = element.val().length + 1;
var max = element.attr("maxlength");
var cond = (46 < event.which && event.which < 58) || (46 < event.keyCode && event.keyCode < 58);
if (!(cond && len <= max)) {
event.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input id="test" size="3" type="number" maxlength="3" onkeypress="test(this.id, event)">
</body>
</html>

Speaking of HTML 4.01 there is no such type as "number".
Speaking of HTML 5 FF and IE do not yet know the number type if http://www.w3schools.com/html5/html5_form_input_types.asp is correct.
/edit: So FF and IE will probably fallback to text and this is why maxlength will work.

I solved problem using this jQuery codes:
$('input[type="number"]').on('keypress', function (e) {
var maxlength = $(this).prop('maxlength');
if (maxlength !== -1) { // Prevent execute statement for non-set maxlength prop inputs
var length = $(this).val().trim().length;
if (length + 1 > maxlength) e.preventDefault();
}
});
Set maxlength attribute for every input[type="number"] that you want, just like text inputs.

for react this works for me if anyone stumbles on here with using react :)
<input type="number" name="expiry" placeholder="Expiry" onChange=
{this.handleInputChange} onFocus={this.handleInputFocus} onInput={(event)=>event.target.value=event.target.value.slice(0,event.target.maxLength)}
maxLength="4" />

for guys who are using React and have landed here:
<input name="maxNumber"
onInput= {(event)=> event.target.value.length > 1 ?
event.target.value =
event.target.value.slice(0, 1)
:
event.target.value
}
type = "number"
/>
In this case, 1 is the maximum length of values. You can put any and change the ones.

Related

How to specify max length of 6 numbers only in input type number field [duplicate]

The maxlength attribute is not working with <input type="number">. This happens only in Chrome.
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
From MDN's documentation for <input>
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
So maxlength is ignored on <input type="number"> by design.
Depending on your needs, you can use the min and max attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern attribute:
<input type="text" pattern="\d*" maxlength="4">
Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
Many guys posted onKeyDown() event which is not working at all i.e. you can not delete once you reach the limit. So instead of onKeyDown() use onKeyPress() and it works perfectly fine.
Below is working code:
User will not be allowed to enter more than 4 digits
<br>
<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==4) return false;" />
I have two ways for you do that
First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:
<input type="tel" />
Second: Use a little bit of JavaScript:
<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />
You can use the min and max attributes.
The following code do the same:
<input type="number" min="-999" max="9999"/>
This works in Android as well
Change your input type to text and use "oninput" event to call function:
<input type="text" oninput="numberOnly(this.id);" maxlength="4" id="flight_number" name="number"/>
Now use Javascript Regex to filter user input and limit it to numbers only:
function numberOnly(id) {
// Get element by id which passed as parameter within HTML element event
var element = document.getElementById(id);
// This removes any other character but numbers as entered by user
element.value = element.value.replace(/[^0-9]/gi, "");
}
Demo: https://codepen.io/aslami/pen/GdPvRY
For React users,
Just replace 10 with your max length requirement
<input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>
how to limit input type max length
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
You can try this as well for numeric input with length restriction
<input type="tel" maxlength="4" />
I once got into the same problem and found this solution with respect to my needs.
It may help Some one.
<input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>
Happy Coding :)
try use tel :
maxlength="5" type="tel"
I wrote a small and clean workaround. Using this function will make it work, as it should
const inputHandler = (e) => {
const { value, maxLength } = e.target;
if (String(value).length >= maxLength) {
e.preventDefault();
return;
}
};
For example, it can be used in React like this:
<input
type="number"
maxlength="4"
onKeyPress={inputHandler}
/>
this code worked for me
<form method="post">
<label for="myNumber">My Number:</label>
<input type="number" maxlength="9" required
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" >
<br><br>
<input type="submit" value="Submit">
</form>
Chrome (technically, Blink) will not implement maxlength for <input type="number">.
The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.
<input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">
DEMO - JSFIDDLE
Here is my solution with jQuery...
You have to add maxlength to your input type=number
$('body').on('keypress', 'input[type=number][maxlength]', function(event){
var key = event.keyCode || event.charCode;
var charcodestring = String.fromCharCode(event.which);
var txtVal = $(this).val();
var maxlength = $(this).attr('maxlength');
var regex = new RegExp('^[0-9]+$');
// 8 = backspace 46 = Del 13 = Enter 39 = Left 37 = right Tab = 9
if( key == 8 || key == 46 || key == 13 || key == 37 || key == 39 || key == 9 ){
return true;
}
// maxlength allready reached
if(txtVal.length==maxlength){
event.preventDefault();
return false;
}
// pressed key have to be a number
if( !regex.test(charcodestring) ){
event.preventDefault();
return false;
}
return true;
});
And handle copy and paste:
$('body').on('paste', 'input[type=number][maxlength]', function(event) {
//catch copy and paste
var ref = $(this);
var regex = new RegExp('^[0-9]+$');
var maxlength = ref.attr('maxlength');
var clipboardData = event.originalEvent.clipboardData.getData('text');
var txtVal = ref.val();//current value
var filteredString = '';
var combined_input = txtVal + clipboardData;//dont forget old data
for (var i = 0; i < combined_input.length; i++) {
if( filteredString.length < maxlength ){
if( regex.test(combined_input[i]) ){
filteredString += combined_input[i];
}
}
}
setTimeout(function(){
ref.val('').val(filteredString)
},100);
});
I hope it helps somebody.
Input type text and oninput event with regex to accept only numbers worked for me.
<input type="text" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>
Try this,
<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
The below code will allow the user to:
Enter digits only in the 0-999 range.
This also restricts the user not to enter more than 3 characters.
When the user enters more than 3 characters then it will clear the textbox.
<input type="number" name="test_name" min="0" max="999" oninput="validity.valid||(value='');">
If you want to do it in a React Function Component or without using "this", here is a way to do it.
<input onInput={handleOnInput}/>
const handleOnInput = (e) => {
let maxNum = 4;
if (e.target.value.length > maxNum) {
e.target.value = e.target.value.slice(0, maxNum);
}
};
In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters.
As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.
To have the field limit the number of characters that can be inserted while allowing the user to be aware of this before the form is submitted (browser should identify value > max otherwise), you will have to (for now, at least) add a listener to the field.
Here is a solution I've used in the past: http://codepen.io/wuori/pen/LNyYBM
maxlength ignored for input type="number"
That's correct, see documentation here
Instead you can use type="text" and use javascript function to allow number only.
Try this:
function onlyNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
<input type="text" maxlength="4" onkeypress="return onlyNumber(event)">
I know there's an answer already, but if you want your input to behave exactly like the maxlength attribute or as close as you can, use the following code:
(function($) {
methods = {
/*
* addMax will take the applied element and add a javascript behavior
* that will set the max length
*/
addMax: function() {
// set variables
var
maxlAttr = $(this).attr("maxlength"),
maxAttR = $(this).attr("max"),
x = 0,
max = "";
// If the element has maxlength apply the code.
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {
// create a max equivelant
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
while (x < maxlAttr) {
max += "9";
x++;
}
maxAttR = max;
}
// Permissible Keys that can be used while the input has reached maxlength
var keys = [
8, // backspace
9, // tab
13, // enter
46, // delete
37, 39, 38, 40 // arrow keys<^>v
]
// Apply changes to element
$(this)
.attr("max", maxAttR) //add existing max or new max
.keydown(function(event) {
// restrict key press on length reached unless key being used is in keys array or there is highlighted text
if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
});;
}
},
/*
* isTextSelected returns true if there is a selection on the page.
* This is so that if the user selects text and then presses a number
* it will behave as normal by replacing the selection with the value
* of the key pressed.
*/
isTextSelected: function() {
// set text variable
text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return (text.length > 0);
}
};
$.maxlengthNumber = function(){
// Get all number inputs that have maxlength
methods.addMax.call($("input[type=number]"));
}
})($)
// Apply it:
$.maxlengthNumber();
Done! Numbers only and maxlength work perfect.
<input maxlength="5" data-rule-maxlength="5" style="height:30px;width: 786px;" type="number" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
This code worked quite nicely for me.
In the input with type="number", you can add the following attribute:
oninput="constrainUserInput(this.id)"
The full input will look like this:
<input type="number" class="test_css" maxlength="4" oninput="constrainUserInput(this.id)" id="flight_number" name="number"/>
Note: You must assign your input and ID for this method to work
Then you can add the following JavaScript to your HTML, which basically replaces any characters that exceed your maxlength attribute with an empty quote (essentially removing them):
function constrainUserInput(id) {
let input = document.getElementById(id);
let value = input.value;
if (value.length > input.maxLength) {
input.value = value.substring(0, input.maxLength);
}
}
The absolute solution that I've recently just tried is:
<input class="class-name" placeholder="1234567" name="elementname" type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />
As per the Neha Jain's answer above ,I just added below code to common area
$(':input[type="number"]').on('input', function() {
if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);
});
then you can use maxlength="4" like text type fields.
<input type="number"> is just that... a number input (albeit, unconverted from a string to float via Javascript).
My guess, it doesn't restrict characters on key input by maxLength or else your user could be stuck in a "key trap" if they forgot a decimal at the beginning (Try putting a . at index 1 when an <input type"text"> "maxLength" attr has already been reached). It will however validate on form submit if you set a max attribute.
If you're trying to restrict/validate a phone number, use the type="tel" attr/value. It obeys the maxLength attr and brings up the mobile number keyboard only (in modern browsers) and you can restrict input to a pattern (i.e. pattern="[0-9]{10}").
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
Use type number with min and handle max with onKeyPress
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
I will make this quick and easy to understand!
Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .
Cheers

How to avoid Decimal values in input type number

How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.
An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle
<form action="#" method="post">
Numbers: <input name="num"
type="number"
min="1"
step="1"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
<input type="submit">
</form>
I ended up checking to see if a user types in a period then preventing the event from propagating.
Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.
<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">
Caution Experimental. Only partially works on chrome:
Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.
<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >
Use pattern attribute
<input type="number" name="num" pattern="[0-9]" title="Numbers only">
For more details http://www.w3schools.com/tags/att_input_pattern.asp
FIDDLE
Just plain example using parseInt()
<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />
Based on other answers here, I tried this:
<input id="storeId" min="0" pattern="[0-9]" onkeypress="return !(event.charCode == 46)" step="1" title="Must be an integer number" type="number" >
I just blocked input of dot, but again this does not block paste.
ASCII DOT . character is 46
<input type="number" onkeydown="return event.keyCode !== 190">
This will Restrict period(.) input.For any Key restriction:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
You guys can try this
This function does not allow user to paste unwanted characters and also disallow user to enter .+-E
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
"."
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-\.]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" >
`
If error occured in your JS. You can add this
`$(document).ready(function() { code });
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" name="quantity">
Try this :
<input type="number" value="" min="0" oninput="this.value=(parseInt(this.value)||0)" onkeypress="return !(event.charCode == 45||event.charCode == 46||event.charCode == 43)" class="form-control" step="any" />
event.key and event.charCode are deprecated features and don't work well with mobile virtual keyboards. I've done some research and this seems to be the easiest way to make it work.
Tested in Chrome and Firefox on Windows, in Chrome on Android and in Safari on iOS and seems to be working perfectly.
document.getElementById("myInput").addEventListener('beforeinput', e => {
if (!(Number(e.data) >= 0 && Number(e.data) <= 9)) {
e.preventDefault();
}
});
/* unnecessary */
#myInput {
width: 24ch;
}
<input type="number" inputmode="numeric" placeholder="only a number can go here" id="myInput">
By the way, this is my first post here, so please tell me if I'm doing anything wrong.
You should post what you have tried when asking questions.
To use integers only, change the following attribute.
step="any"
to
step="1"
A simple regex can help sort with this issue .
var re = new regExp('[.]+) ;
if(!re.test(num)){listOfNumbers.push(num)};
not letting the user type in a '.' on the input might not be a viable option when you are dealing with multiple cultures and interpretations of '.'.
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
return false;
return true;
}
#Html.TextBoxFor(model => model.num, new { #class = "form-control input-sm",#maxlength = 5 ,#oninput = "this.value = this.value.replace(/[^0-9]/g, '');"})
In MVC, above solution works.

Allow 2 decimal places in <input type="number">

I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type="number" required name="price" min="0" value="0" step="any">
Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
In case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
For currency, I'd suggest:
<div><label>Amount $
<input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by #SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.
You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.
function enforceNumberValidation(ele) {
if ($(ele).data('decimal') != null) {
// found valid rule for decimal
var decimal = parseInt($(ele).data('decimal')) || 0;
var val = $(ele).val();
if (decimal > 0) {
var splitVal = val.split('.');
if (splitVal.length == 2 && splitVal[1].length > decimal) {
// user entered invalid input
$(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
}
} else if (decimal == 0) {
// do not allow decimal place
var splitVal = val.split('.');
if (splitVal.length > 1) {
// user entered invalid input
$(ele).val(splitVal[0]); // always trim everything after '.'
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />
I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.
just adding step=".01", sorted my issue.
<input type="number" class="form-control" name="price" step=".01">
Use this code
<input type="number" step="0.01" name="amount" placeholder="0.00">
By default Step value for HTML5 Input elements is step="1".
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):
function handleNumberChanged (e) {
const fixed = parseFloat(e.target.value).toFixed(2).toString()
if (fixed.length < parseFloat(e.target.value).toString().length)
e.target.value = fixed
}
This question has been already answer but you can allow decimals
with the step attribute.
you can read more about it here: Allow-decimal-values
This is the solution I've came up with which also stops the user from typing in more that 2 decimals, which a lot of the solutions mentioned above, don't protect against
html:
<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"
Javascript:
function priceCheck(element, event) {
result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
if (result) {
let t = element.value;
if (t === '' && event.charCode === 46) {
return false;
}
let dotIndex = t.indexOf(".");
let valueLength = t.length;
if (dotIndex > 0) {
if (dotIndex + 2 < valueLength) {
return false;
} else {
return true;
}
} else if (dotIndex === 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Only 3 decimal point input value in textbox using Javascript.
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
<input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
On Input:
<input type="number" name="price" id="price" required>
On script:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});

How to prevent a user from entering negative values in Html input

I am using the following html input element for collecting the product quantity in Html page but the user can still go ahead and manually enter negative value. For example: I selected the the textbox and entered -100 and input field took it without complaining about it.
How can I prevent user from entering 0 and non-negative values in Html input element?
<input type="number" id="qty" value="" size="3" min="1" />
Due to the <input type="number"> still not being widely well supported, you are still better off using a text input. Preventively you could disallow any characters which are not numbers with the keypress event and e.preventDefault(). However be sure that if you want to support legacy browsers (IE8-), there are a number of inconsistencies to take into account regarding returned key codes/ char codes. If you also want to disallow pasting non-number content, you can do so with the paste event and e.clipboardData.getData('plain/text') (for a complete implementation see here)
Test with the code below:
var myInput = document.getElementsByTagName('input')[0];
myInput.addEventListener('keypress', function(e) {
var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
function keyAllowed() {
var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50,
51,52,53,54,55,56,57,91,92,93];
if (key && keys.indexOf(key) === -1)
return false;
else
return true;
}
if (!keyAllowed())
e.preventDefault();
}, false);
// EDIT: Disallow pasting non-number content
myInput.addEventListener('paste', function(e) {
var pasteData = e.clipboardData.getData('text/plain');
if (pasteData.match(/[^0-9]/))
e.preventDefault();
}, false);
<input type="text">
You can validate the value with regex with the pattern attribute:
<input type="number" pattern="^[1-9]\d*$" name="qty">
You can use the built-in form validation validity.valid, user won't be able to enter or paste negative values. Also user won't be able enter decimals. More info here
<input type="number" min="1" oninput="validity.valid||(value='');"/>
try this :
<input type="number" min="0">

Is there a minlength validation attribute in HTML?

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.
I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`
minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.
My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}
I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.
I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.
Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />