Minimum and Maximum length of User Input - javascript

I have a form in which a user enters a 13 digits numeric value and i try to use minlength attribute but its not working. So i try javascript and it works fine but when the focus losses from Input then the function onblur calling again and again. the code is under
HTML
<input type='number' id='cnc' pattern='[0-9]{13,13}' name='cnic' oninput="javascript: if (this.value.length > 13) this.value = this.value.slice(0, 13);" minlength="13" onblur="checkLength(this);" placeholder="Enter CNIC without dashes: e.g 6110122334455" class='form-control' required value="<?php echo isset($_POST['cnic']) ? htmlspecialchars($_POST['cnic'], ENT_QUOTES) : ""; ?>" />
Javascript
function checkLength(el) {
if (el.value.length != 13) {
alert("CNIC length should be 13 digits");
document.getElementById("cnc").focus();
document.getElementById("cnc").select();
}
Now i want that the control/cursor to the input field if user not entered 13 digit code and moves to other input field

Try this regex method to verify the Pakistani CNIC format:
jQuery('#cnic').blur(function(){
var input_text = jQuery(this).val(),
myRegExp = new RegExp(/\d{5}-\d{7}-\d/);
if(myRegExp.test(input_text)) {
//if true
jQuery('#cninc_msg').text('Correct');
}
else {
//if false
jQuery('#cninc_msg').text('Enter CNIC in correct format. 12345-1234567-1');
}
});
jQuery('#cnic2').blur(function(){
var input_text = jQuery(this).val();
if(input_text.length != 13 ){
jQuery('#cninc2_msg').text('Error');
}
else{
jQuery('#cninc2_msg').text('OK');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="cnic" name="cnic" placeholder="42212-1234567-1" />
<span id="cninc_msg"> </span>
Without Dashes simply check this
<input type="text" id="cnic2" name="cnic" placeholder="4221212345671" />
<span id="cninc2_msg"> </span>
This is just a basic example. You can use this on on key up or onkeyDown events as per your requirements.

minlength is not yet supported by any browser. Try this instead

Related

jquery validation allow to enter code between user1 to user100

This is my the example where user can enter the code between 1 to 100 only otherwise return false.
var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/;
$(document).on('change','#code',function(){
if (!regexCode.test($("input#code").val())) {
alert("Please enter valid code");
$("input#code").focus();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required>
Now it accepting digits between 1 to 100 but I need it to accept the code e.g between
user1 to user100 only otherwise return false.
lot of solution with : regexp
var regexCode = /^user(?:[1-9][0-9]{0,1}|100)$/;
$(document).on('change','#code',function(){
var result = $("input#code").val();
if (!regexCode.test($("input#code").val())) {
alert("Please enter valid code");
$("input#code").focus();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required>
You can use this regex /^[1-9][0-9]$|^100$/ explain:
^[1-9][0-9]? should mens starts digit with two or one (first doesn't accept 0 )range number - 0 --> 99
| or operator
^100$ start and end only with the number 100
also think to remove last added number from value using :
value = value.substring(0, value.length - 1);
$(this).val(value);
Belw in snippt I've used on Input event to check for every keyboard input
var regexCode = /^[1-9][0-9]?$|^100$/;
$(document).on('input','#code',function(e){
let value = $(this).val();
if (!regexCode.test($(this).val())) {
alert("Please enter valid code");
value = value.substring(0, value.length - 1);
$(this).val(value)
$("input#code").focus();
return false;
} else {
$("#output").html("user"+value)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required> rang betwwen 0-100
<br><br>
user id = <span id="output"></span>
You can use HTML Pattern for this purpose.
<input type="text" name="code" id="code" placeholder="code" pattern="user[0-9]{1,2}" required />

How to input phone no in this 'xxx-xxx-xxxx' format in number input field

I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>

How can I change HTML5 form validation default error messages for min and max?

I found this answer for changing error message for invalid values How can I change or remove HTML5 form validation default error messages?.
I need to show different message for value less than min and more than max.
<input type="number" name="test" step="any" min="0.01" max="10.0">
If user enters -1, it should say "Please enter positive value".
If user enters 20, it should say "Value cannot be more than 10".
There may be some fancy API-driven way to do it, but if the title is displayed when the input doesn't match a pattern, you can just modify the the title on change.
To support decimals, you'll need some fancier regex.
*I included the form tag so the validation would work in the snippet
document.querySelector('input').addEventListener('change', (e) => {
if (e.target.value > 10) {
e.target.setAttribute('title', "Value cannot be more than 10");
} else if (e.target.value < 0) {
e.target.setAttribute('title', "Please enter a positive value");
} else {
e.target.setAttribute('title', "Please enter a number");
}
})
<form><input type="text" required="" pattern="10|[0-9]" value="" title="This is an error message" /></form>
With the HTML5 form validation (from your link) you can use a custom message by using the invalid event listener on the input element.
var myInput = document.getElementById("myInput");
myInput.addEventListener("invalid", validate);
myInput.addEventListener("keyup", validate);
function validate() {
var val = parseFloat(this.value);
var min = parseFloat(this.min);
var max = parseFloat(this.max);
if (val < min) {
this.setCustomValidity('Please enter a positive number');
} else if (val > max) {
this.setCustomValidity('Value cannot be more than ' + max);
} else {
this.setCustomValidity("");
}
}
<form>
<input id="myInput" type="number" name="test" step="any" min="0.01" max="10.0">
<button type="submit">Submit</button>
</form>

How to use javascript to validate the input field for restricting numbers only and setting the range as maximum and minimum

On event change the overflow value must get rejected.
I have an input box in my form, where I want to restrict the user to enter only the numbers between 0 and 99999 only. But I don't want to disable the tab button functionality. The below code is working fine for "NUMBERS only" but it won't allow to use Tab button as well. Also it's not checking the overflow condition if someone enters number bigger than 99999.
<script>
function myIdFunction() {
var txt = "";
if (document.getElementById("EmpId").validity.rangeOverflow) {
txt = "Value too large";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<input type="text" name="id" id="EmpId" ng-model="EmpId" max="99999"
onchange="myIdFunction()" onkeypress="return IsNumeric(event);"
ondrop="return false;" onpaste="return false;" ng-disabled="!edit"
placeholder="EmpId" required>
<span id="error" style="color: Red; display: none">* Input digits (0 -)</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) ||
specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
<input type=number min=0 max=99999>
Brought to you by:
For the specification see:
WHATWG HTML, section 4.10.5.1.13
For supported browsers see:
Can I use: Number input type
The Current State of HTML5 Forms: The min, max, and step Attributes
For older browsers use:
number-polyfill
(A polyfill for implementing the HTML5 <input type=number> element in browsers that do not currently support it.)
Live enforcement of correct values
If you don't want the user to be able to enter incorrect values while typing:
var last = '';
input.addEventListener('input', function () {
if (this.checkValidity()) {
last = this.value;
} else {
this.value = last;
}
});
See: DEMO.

How to restrict a textbox to accept 10 alphabetic characters only using javascript?

How to restrict a textbox to accept 10 characters only.If we enter 11th character, it should give a message saying 'you are allowed to enter 10 characters only'.
Try with this function:
function check_content(){
var text = document.getElementById("your_textbox_id").value;
if(text.length > 10){
alert('Length should not be greater than 10');
return false;
} else {
return true;
}
}
Try this code:
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
Code for textbox.
<input name="mytext" type="text" value='' id="mytext" onkeyup="TextLimit()">
and add a javascript function on keyup event of textbox.
<script>
function TextLimit(){
var text = document.getElementById('mytext');
if (text.value.length >= 10){
alert('you are allowed to enter 10 characters only');
}
}
</script>

Categories

Resources