I want minlength=8 and maxlength=14, how can I achieve this validation.
html:
<input type="text" name="354" id="field">
jQuery:
$("input[name=354]").keypress(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits only").show().fadeOut("slow");
return false;
}
});
Now with HTML5 you can use the properties minlength and maxlength.
<input type="text" minlength="8" maxlength="14" name="354" id="field">
You can use HTML5 attributes minlength and maxlength to manage input text length. But if you want to use JQuery to do this work, see this example
var minLength = 3;
var maxLength = 10;
$("input").on("keydown keyup change", function(){
var value = $(this).val();
if (value.length < minLength)
$("span").text("Text is short");
else if (value.length > maxLength)
$("span").text("Text is long");
else
$("span").text("Text is valid");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<span></span>
Related
I am doing some validations for the input type.
<input
type="number"
min="0"
decimal-places=""
ng-model="candidate.ctc"
class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
id="ctc"
placeholder="CCTC"
autocomplete="off"
required="">
Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.
So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?
Here's a working solution:
http://jsfiddle.net/qoL16sup/
Directive:
decimalPlaces.$inject = ['$filter','$locale'];
function decimalPlaces($filter,$locale){
return {
require: 'ngModel',
link: function(scope,element,attrs,ngModelCtrl){
var groupSep = $locale.NUMBER_FORMATS.GROUP_SEP;
var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
var decimalPlaces = scope.$eval(attrs['decimalPlaces']) || 0;
var pattern = decimalPlaces > 0 ?
new RegExp('^\\d*(\\'+ decimalSep +')?[0-9]{0,' + decimalPlaces + '}$') : new RegExp('^\\d*$');
element.bind('keypress',function(e){
var lastChar = e.charCode!==0?String.fromCharCode(e.charCode):'';
var selectionStart = element[0].selectionStart;
var selectionEnd = element[0].selectionEnd;
var newVal = element.val().slice(0,selectionStart) + lastChar + element.val().slice(selectionEnd);
if(!pattern.test(newVal)){
e.preventDefault();
}
});
element.bind('blur',function(){
var value = ngModelCtrl.$viewValue || ngModelCtrl.$modelValue;
if (ngModelCtrl.$isEmpty(value)) return null;
if(pattern.test(value)){
element.val($filter('number')(value,decimalPlaces));
}else{
element.val('');
ngModelCtrl.$setViewValue('');
ngModelCtrl.$commitViewValue();
}
});
element.bind('focus',function(){
var value = ngModelCtrl.$modelValue || ngModelCtrl.$viewValue;
if (ngModelCtrl.$isEmpty(value)) return null;
element.val(value);
});
ngModelCtrl.$parsers.unshift(function(value){
if (ngModelCtrl.$isEmpty(value)) return null;
if(pattern.test(value)){
value = parseFloat(value);
if(decimalPlaces){
value = value.toFixed(decimalPlaces);
}else{
value = Math.floor(value);
}
return parseFloat(value);
}else{
return null;
}
});
if (angular.isDefined(attrs.min)) {
var minVal = scope.$eval(attrs.min);
ngModelCtrl.$validators.min = function(value) {
return ngModelCtrl.$isEmpty(value) || angular.isUndefined(minVal) || value >= minVal;
};
}
if (angular.isDefined(attrs.max)) {
var maxVal = scope.$eval(attrs.max);
ngModelCtrl.$validators.max = function(value) {
return ngModelCtrl.$isEmpty(value) || angular.isUndefined(maxVal) || value <= maxVal;
};
}
}
}
}
HTML:
<form name="myForm" novalidate autocomplete="off">
<label>
Decimal places = 0
<input
type="text"
name="input1"
decimal-places="0"
ng-model="model.input1"
autocomplete="off"
required>
</label>
<br/> <br/>
<lable>
Decimal places = 2:
<input
type="text"
name="input2"
decimal-places="2"
ng-model="model.input2"
autocomplete="off"
required>
</lable>
<br/> <br/>
<lable>
Decimal places = 2, min = 100, max = 10000:
<input
type="text"
name="input3"
decimal-places="2"
min="100"
max="10000"
ng-model="model.input3"
autocomplete="off"
required>
</lable>
</form>
You can use ngPattern to validate the input. But it won't prevent the user from typing a negative number. Use a following function to avoid typing a negative value.
$(document).ready(function(){
$("#ctc").keydown(function(e){
if (e.key == "." || e.key=="-") {
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Preventing negative values</p>
<input type="number" min="0" max="10" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition" id="ctc" placeholder="CCTC" autocomplete="off" style='width:300px' required=""/>
You should use like this,
var number = document.getElementById('ctc');
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>
So basically I have a for loop and I am trying to get it to run x amount of times. Depending on what the user inputs. The issue I am having is how to get the user input and also make sure that its a number not any other type of input. making them try again if its wrong.
It's simple really
Input Number : <input id="numberinput" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
<button id="btn" onclick="doAction()">
Send
</button>
<script>
var doAction = function () {
var input = document.getElementById('numberinput');
var times = parseint(input.value);
for(var i = 0; i < times; i++) {
//do whatever you need to do
}
}
</script>
In HTML5 you can use <input type="number"> to restrict an input to numeric characters only.
For older browsers, that are not HTML5-compatible, use <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>. This utilizes Javascript to make sure that only numeric input is accepted into the input box.
Check out the snippet below for both solutions in action:
Javascript-based:<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<br><br>
HTML5 solution (preferred):<input type="number">
Fiddle
HTML
<input type="number" id="myInput">
<button id="myButton">Run Loop</button>
Javascript
$('body').on('click', '#myButton', function() {
var input = $('#myInput').val();
for(var i = 0; i < input; i++) {
alert('You have written inside input field: ' + input + ". This is Alert #" + (i+1))
}
});
To get the value from the input, you can use the value property of the input element.
To make sure the input is a number, you can specify type="number" if HTML5 is supported as mentioned in Angelos Chalaris's answer.
document.getElementById('btn').onclick = function(){
var totalIterations = parseInt(document.getElementById('input').value);
var output = document.getElementById('output');
output.innerHTML = '';
for(var i = 1; i <= totalIterations; i ++) {
var item = document.createElement('div');
item.innerHTML = i;
output.appendChild(item);
}
};
<input id="input" type="number"/>
<input id="btn" type="button" value="Do loop"/>
<div id="output"></div>
Here is an example using user input dialog:
var input, parsedInput = 0;
do {
input = prompt("Please enter valid number", "1");
parsedInput = parseInt(input);
} while(isNaN(parsedInput) || parsedInput < 0);
// keep trying on invalid input or negative number
for( i=0; i< parsedInput ; i++){
console.log("loop " + i);
}
HTML:
<input type="text" name="somefield" id="someid" value="10" />
JS:
var userInput = document.getElementById('someid').value;
if( Number.isInteger(parseInt(userInput)) )
{
// do something
}
Also, Number.isInteger() does not work on Internet explorer 11 or earlier.
I have a set of input elements within 2 span block. I need to automatically select next input element by using onKeup(). This works fine until span tag is found. After that it is not detecting.
In the following code next input element is detected until 3rd input box after that it is not detected.
Can any one help with this?
http://jsfiddle.net/et3escuh/8/
<span>
<input id="opnamenummer6" class="form-control" type="text" name="opnamenummer6" value="" maxlength="1">
<input id="opnamenummer7" class="form-control" type="text" name="opnamenummer7" value="" maxlength="1">
<input id="opnamenummer8" class="form-control" type="text" name="opnamenummer8" value="" maxlength="1">
</span>
<script type="text/javascript">
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
// if we've filled up this input, go to the next if only numerics are entered.
if ( (currentLength == maximumLength) && ((event.which >= 48 && event.which <= 57) || (event.which >= 96 && event.which<= 105))) {
$this.next().select();
}
//go to previous input if Backspace or Delete buton is pressed
if(event.which == 8 || event.which == 46) {
$(this).val('');
$(this).prev('input').select();
}
});
</script>
Don't use next(), use eq() and add or subtract to the index
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
if ( (currentLength == maximumLength) && (!isNaN(this.value))) {
$('input').eq($(this).index('input') + 1).select();
}
if(event.which == 8 || event.which == 46) {
$(this).val('');
$('input').eq($(this).index('input') - 1).select();
}
});
FIDDLE
How can I validate only the numbers 0 to 10?
I have this function which validate all the numbers.
function compruebacampo(e, campotexto) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
}
Thanks a lot for your help.
http://jsfiddle.net/6faHh/
The best JavaScript is no JavaScript.
<input type="number" min="0" max="10" />
<input id="your_input_id1" type="number" min="0" max="10" />
<input id="your_input_id2" type="number" min="0" max="10" />
<script>
var input1 = document.getElementById("your_input_id1");
var input2 = document.getElementById("your_input_id2");
function testNums(evt) {
var num = parseInt(evt.target.value, 10);
if (typeof num === "number" && num < 11 && num > -1) {
evt.target.value = num
} else {
evt.target.value = ''
}
};
input1.onkeyup = testNums;
input2.onkeyup = testNums;
</script>
Example js fiddle
http://jsfiddle.net/g63b5/3/
In this example entry is prevented and the box is cleared if the range is incorrect or anything other than number entered, also uses native html5 input for supported devices.
Edit: wasn't 100% sure what your comment meant, so I just added the handler to more inputs, in case that is what you were asking.