I am trying to implement maxlength in PhoneGap for Android but am not able to restrict characters cause it never fetches proper character code. Character code for delete key from below code is same as character code for any other key.
$(".limit-thirtyfive").bind("paste", function(e) {
// access the clipboard using the api
if (e.keyCode != 8 || e.keyCode != 46) {
if ($(this).val().length >= 33) {
$(this).val($(this).val().substr(0, 33));
}
}
});
$('.limit-ten').keyup(function(e) {
if (e.keyCode != 8 || e.keyCode != 46) {
if ($(this).val().length >= 10) {
$(this).val($(this).val().substr(0, 10));
}
}
});
Length Restriction on General
You can simply use maxlength attribute of the input element you are referring to.
<input type="text" maxlength="5"/>
Restricting Special Characters
For getting this done, you may want to use onchange event of input fields. The example below restricts user to enter character 'a'.
$('your_input').onchange(function(){
$(this).val($(this).val().replace(/a/g, ''));
});
Related
When using type="number" on an input field, regex validation does not appear to work.
<input type="number" step="any" min="0" max="24" value="0">
The new broswer based validation using step, min, max works as expected. However this is not consistent accross browsers?
http://jsfiddle.net/EkL3k/1/
QUESTION
How to make a number field validate using regular expression?
I'm also interested in other factors that differentiate a number and text field if anyone has information.
NOTES
I have discovered that checking for an empty string causes validation to fire IF the conditions on the number field are not met.
A number field performs its own validation, if it contains a non-numerical character, the value will automatically be removed until a correct value is given. You can see this with a console.log(value).
So you could also check for an empty string
function check(value, msg) {
var valid = ((value != '') && /^\d*\.?\d*$/.test(value));
if (valid) {
document.getElementById(msg).style.display = "none";
} else {
document.getElementById(msg).style.display= "inline";
}
return valid;
}
http://jsfiddle.net/EkL3k/6/
RegEx does not work because the returned value is a number, not a string. It works 'as expected' when you force the returned value to string format:
var valid = /^\d*\.?\d*$/.test(String(value));
You might want to read How to get the raw value an <input type="number"> field? as it suggests you don't have to validate a type=number input.
add this code and add an id to your input.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
http://codepen.io/anon/pen/IDEGu
Ok Well. I want to restrict input field to accept only numbers with maxlength 5 characters.
My Try:
HTML
<input type="number" maxlength="5" onKeyDown="numbersOnly(event);/>
<input type="text" pattern= "[0-9]" onKeyDown="numbersOnly(event);/>
Javascript
function numbersOnly(event,length)
{
return event.ctrlKey || event.altKey
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46)
|| (event.keyCode>47)&&(event.keyCode<=57) ;
}
All works in firefox. But when i check with safari ipad, it accepts special characters like ()#!#$&. I used alert function for debugging. It returns same keyCode for # and 2 , 3 and # and so on. I tried keyUp,keyPress events and event.charCode,event.which,event.key. Nothing works
So how to differentiate it and i need support for backspace , enter , delete, arrow keys also.
I've made this once and haven't been able to break it. Tested on iPad.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
This also accounts for copy/paste and drag and drop text, which people often forget. You can add the max-length to the onchange.
Using type="number" on an input prevents you from reading non-numerical input values via input.value (it will then return an empty string) and thus eliminates the possibility of filtering invalid user input (+-.e) while keeping the valid numbers. Thus you have to use type="text". Example:
$('.input-number').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input-number" type="text" maxlength="5">
If you want the text-cursor not to move when pasting or typing invalid input, have a look at my answer to a similar question here: HTML input that takes only numbers and the + symbol
Be careful the iOS keyCodes are not the same desktop computers. See IOS keyCodes in Javascript
<input type="number" maxlength="5" onkeypress="numbersOnly(event);/>
var numbersOnly = function(event) {
if(event.keyCode >= 48 && event.keyCode <= 57) {
return false;
} else {
event.preventDefault();
}
}
If you want to enter the only numbers in input type number fields. this will be helpful, It will work on iPhone and iPad as well.
$(document).on('keypress', 'input[type="number"]', function (event) {
return event.code.includes('Digit') || event.code.includes('Numpad') || event.code.includes('Period');;
});
I have to validate the textbox to enter only alpha numeric characters.
The function validateAlphaNumeric(evt, txtbox) fires onkeypress event on textbox.
Below is the function written in Javascript.
But I am not able to get the value of the textbox if I do Ctrl+V. I need to validate if user pastes.
Can any one suggest me on this?
function validateAlphaNumeric(evt, textBox) {
/* File Description : Numbers,Characters,Hyphen(-),Slash(/)and Space */
var charCode;
charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode == 8 || charCode >= 48 && charCode <= 57 || charCode == 45) {
return true;
}
else {
var errorMsg = document.getElementById(textBox.id + 'Error');
if (errorMsg != null) {
errorMsg.innerText = "Please Enter Alpha – Numeric Characters only";
}
return false;
}
}
I have found an answer:
Try this on onpaste event.
Surely will work out.
I tried this:
function onPaste(evt, textBox) {
pastedText = window.clipboardData.getData('Text');
if (pastedText matches regExp) {
return true;
} else {
//display error msg
return false;
}
}
Regards..
validate text box on onblur() event of that TextBox. your problem will sure get solved.
from html5 on there is the oninputevent which does exactly what you want.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput
In the handler, check that the value property of the text box contains only allowed characters.
Note that IE9 has buggy support for this event - basically it doesn't recognize character deletion, but it doesn't affect you because you can't make the text invalid just by removing stuff. See here for more detail:
http://help.dottoro.com/ljhxklln.php
If you can't use oninput because you really need to support IE8-IE7 (hint: you don't really want to) you can instead fix your code by listening to the onpaste event too to get text paste events.
I need to stop accepting input (keystrokes) on an HTML form input field when the length limit has been reached. In straight-up HTML I can do this with maxlength="3" or whatever the length is, but I would like to handle it through Javascript if possible so I can do it together with the next requirement.
I also need to filter the input so that if a field is numeric only numbers can be typed, and if there's a mask or regex any inputs conform to the mask/regex.
Is there a "standard" way to do this in, Javascript, particularly in Dojo 1.9? (I know everybody uses JQuery but we use Dojo because.)
For dojo, if you need any sort of validation, I would use the ValidationTextBox, which takes "maxLength" as a property AND allows for all sorts of nifty validation schemes. The reference for ValidationTextBox is here:
http://dojotoolkit.org/reference-guide/1.9/dijit/form/ValidationTextBox.html
I used pure Javascript because I am not familiar with Dojo, but these event listeners can probably be cleaned up with Dojo.
var input = document.getElementsByTagName('input')[0],
error = document.getElementById('error');
input.addEventListener('keypress', function(e) {
if(e.which < 48 || e.which > 57) {
e.preventDefault();
error.innerHTML = 'Must be a digit';
} else if(e.target.value.length >= 3) {
e.preventDefault();
error.innerHTML = 'Cannot be more than 3 digits';
} else {
error.innerHTML = '';
}
});
We listen to a keypress and then, to make sure it is a digit, we seek that the key pressed was between 48-57 (0-9). If not, then we prevent the key press and show an error. Then we check the input's current length. If it is too long, then prevent the key press and show an error. Otherwise, it worked and we allow the event and clear the error.
You maybe looking for this:
<input id="text" type="text"/>
$('#text').on('keypress',function(e){
var numero = this.value.length;
console.log(this.value.length);
if (e.which != 8 && e.which < 48 || e.which > 57)
{
return false
}
else if (numero === 3 && e.which != 8){
return false //alert user here
}else{
return true // allow backspace only (8)
}
}
);
DEMO
I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
html
<input type="text" class="hulk" value="" />
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});