phone number validation with different first letters - html

I'm trying to validate hungarian phone numbers which are a little bit harder than other nubmers because we accept 2 types of them:
examples:
+36201234567
+36301234567
+36701234567
but these ones are also valid:
06201234567
06301234567
06701234567
I checked the overflow questions already but couldn't find any solution for the first letter if I can accept '+' and '0' aswell.
This is my code which only accepts the '+' format atm.
<input type="tel" pattern='[\+](36)(20|30|70)\d{7}' class="form-control" id="phone" name="phone" placeholder="+36301234567" required="required">

You can make another comination using | like this:
pattern="([\+](36)(20|30|70)\d{7})|((06)\d{9})"
And also as #grumpy said the best practice is to remove all chars that are not numbers
You can also add a JS function like this with onkeypress events like this onkeypress="return Validate(event)"
`function Validate(event) {
var regex = new RegExp("^[0-9+]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}`

Check this regex: ((?:\+?3|0)6)(?:-|\()?(\d{1,2})(?:-|\))?(\d{3})-?(\d{3,4}). It accepts all kinds of Hungarian phone numbers.
<input type="tel" pattern='((?:\+?3|0)6)(?:-|\()?(\d{1,2})(?:-|\))?(\d{3})-?(\d{3,4})' class="form-control" id="phone" name="phone" placeholder="+36301234567" required="required">

Related

validate input using regex pattern

I want to validate phone number like this
08xxxxxxxx
08xxxxxxxxxx
08xxxxxxxxxxxxx
first and second digit must be 08 and following with other digits minimum 10 digit and maximum 15 digit
I already tried this code
<form>
<input type="tel" name="no_hp" class="form-control" pattern="[0]{1}[8]{1}[0-9]" maxlength="15" oninvalid="this.setCustomValidity('Nomor telepon harus di awali dengan 08 dan minimal 10')" required>
<input type="submit">
</form>
in below video, I try to input 089 and it successes but try without minimum 10 digit
but in below video If I try to input wrong first number like 189 and then I update to right number same with first video 089, its still says number is wrong.
so why after I correct format the number (leading by 08), it still says number is wrong? how to fix that?
I think you can use the following regex as a pattern on the input field directly or use javascript to do the same and show a warning message to the user.
JS Approach
const regex = new RegExp('^08[0-9]{8,13}$', 'gm');
if (regex.test('088884444714255')) {
console.log('valid number');
}else{
console.log('invalid number');
}
if (regex.test('0888844447142555')) {
console.log('valid number');
}else{
console.log('invalid number');
}
if (regex.test('078844447142555')) {
console.log('valid number');
}else{
console.log('invalid number');
}
HTML Pattern Approach
<form>
<input type="tel" name="no_hp" class="form-control" pattern="^08[0-9]{8,13}$" oninvalid=" this.setCustomValidity('Nomor telepon harus di awali dengan 08 dan minimal 10')" oninput="this.setCustomValidity('')" required>
<input type="submit">
</form>

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);
});

Is it possible to configure a required field to ignore white space?

The required attribute in HTML5 is very handy:
<input type="text" required>
But it still allows users to enter white space only.
Is there an HTML-only solution to this?
Use the pattern attribute combined with the required attribute. And be sure to include a title attribute as well, since most browsers insert the title text into the validation pop-up bubble.
<input required pattern=".*\S+.*" title="This field is required">
The .*\S+.* pattern requires at least one non-whitespace character, but also allows whitespace characters (spaces, tabs, carriage returns, etc.) at the beginning or end. If you don't want the user to be able to put whitespace at the beginning/end, then use this instead:
<input required pattern="\S(.*\S)?" title="This field is required">
Try the pattern attribute. You'll need a regex which specifies 'at least one character'.
You probably want this:
<input type="text" required pattern="\S(.*\S)?">
(At least one non-whitespace character and no whitespace at the beginning or end of the input)
Or if whitespace at the beginning and end are fine, then this:
<input type="text" required pattern=".*\S.*">
step 1
create a Javascript function:
function ignoreSpaces(event) {
var character = event ? event.which : window.event.keyCode;
if (character == 32) return false;
}
Step 2
use it on any text-input field in HTML.
<input type="text" id="userInput" onkeypress="return ignoreSpaces(event)">
Working example :
index.html
<html>
<body>
<input type="text" onkeypress="return ignoreSpaces(event)">
<script>
function ignoreSpaces(event) {
var character = event ? event.which : window.event.keyCode;
if (character == 32) return false;
}
</script>
</body>
</html>

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