What would be the easiest way to allow only letters/numbers in a textbox. We are using JS/jQuery, but don't want to use a validation plugin?
My solution was this:
jQuery('input[type="text"]').keyup(function() {
var raw_text = jQuery(this).val();
var return_text = raw_text.replace(/[^a-zA-Z0-9 _]/g,'');
jQuery(this).val(return_text);
});
Every time a user tries to enter anything other than a number, letter, space or underscore the function returns a string with the removed banded characters.
You can use a simple regex on form submit to evaluate the contents of the text box, show an error, and stop the form submit. Make a function out of the check and you can also apply it when the text box loses focus. Do this very often and you'll find that you've reimplemented the validation plugin.
$(function() {
$('form').submit( function() {
return validateTB( $('#textbox'), true, $('#textboxError') );
});
$('#textbox').blur( function() {
validateTB( $(this), true, $('#textboxError') );
});
function validateTB(tb,required,msg) {
var $tb = $(tb);
var re = '/^[a-z0-9]';
if (required) {
re += '+';
}
else {
re += '*';
}
re += '$/';
if ($tb.val().match(re) == null) {
$(msg).show();
return false;
}
$(msg).hide();
return true;
}
});
If you don't wanna use plugins - What about some plain old JS validation?
I posted about this on my blog a while ago --> http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html
You'll see that the function in my proposed solution takes a input field ID and a regex (and you'll have to come up with a regEx for your validation needs, should be pretty trivial if you want only aplhanumeric) and sets the background of the control to green or red depending on the outcome of the validation. I know it's not perfect but I think it's enough to get you going, and you can use it as a starting point to roll your own.
I am sure there are mote elegant solutions using jQuery or plain JS but something along these lines has been working pretty well for me so far.
Hope it helps.
A variant on Ian's answer is a little more lightweight and shorter:
function onlyAllowAlphanumeric() {
this.value = this.value.replace(/[^a-zA-Z0-9 _]/g, '');
});
$('input[type="text"]').keyup(onlyAllowAlphanumeric);
Since tvanfossen's snippet triggers only on submit and Ian's is not as pretty as it could be, I just want to add a more cleaner approach:
HTML:
<input id="myinput" type="text">
JS (jquery):
$('#myinput').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This is a simple solution that will check the input on keyup and remove unwanted characters as the user types:
<input class="usr" type="text id="whatever" name="whatever" />
$(".usr").keyup(function() {
var n = $(this).val();
if ( n.match("^[a-zA-Z0-9 ]*$") == null ) {
$(this).val(n.slice(0,-1));
}
});
The regex can be altered to suit specifications.
Related
Im trying to exclude the vertical bar '|' from my input field called Comments, although i still want to keep basic punctuation like , . : ; - im getting stuck on how to keep some special characters but remove another. In not strong with Regular Expression, hoping some fresh eyes will help.
This is what Ive got so far;
$('#comments').keydown(function (e) {
var k = String.fromCharCode(e.which);
if (k.match(/[^a-z A-Z0-9\x08]/g))
e.preventDefault();
});
The following code works. I have no idea why the code for the pipe character is 220 and not 124, but there you go!
var $comments = $('#comments');
var pipeKeycode = 220; // I cannot figure out why
$comments.on('keydown', function(e) {
if (e.which === pipeKeycode) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Comments: <input id="comments"></label>
To prevent user from typing |.
I don't prevent user from pasting a string with |, but after user gets out of the field, I remove that character in blur:
$('#comments').keydown(function (e) {
if (e.key === '|')
e.preventDefault();
});
$('#comments').blur(function (e) {
e.target.value = e.target.value.replace(/\|/g, '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="comments">
Before you read furtherly, look at my answer and Priyal Pithadiya answer for two different methods on how you can do this.
I have a client that is not satisfied with the solution I got from yesterdays answer on here. Basically I have this script that prevents non number characters from being inserted in an input. It works perfectly when you type but I have a problem here I cannot figure out how to prevent non numbers from being pasted in.
My client has stated that he want to avoid using input number since that was the solution that was offered here but for personal reasons he said he needs to use input text.
If I have to change my code to get a result like this I will.
Please note, I cannot use jQuery, my solution must be javascript only.
This is my code:
//Prevent non numbers from keypress
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
//Prevent non numbers from being pasted only numbers can be pasted
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(){
//???
}
<input type="text" id='numbers-only'>
# try with given solution ,
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
in-line js:
<input type="text" pattern="\d{1,}" onkeyup="this.value = this.value.replace(/[^0-9]/g, '')" />
You can use onpaste Event if you want.
<input type="text" id='numbers-only' onchange="removeChars()">
function removeChars() {
var input = document.getElementById('numbers-only');
input.value = input.value.replace(/[^0-9]/g, '');
}
Thanks Priyal Pithadiya for your help I will like to post two versions of Priyal Pithadiya examples from earlier and now which includes two versions one is with
a onpaste example and the other one is based on using an addEventListener by paste this is for any future readers reading this. All credit goes to Priyal Pithadiya.
With onpaste
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
function myFunction(e) {
var el = e;
setTimeout(function() {
el.value = el.value.replace(/\D/g, '');
}, 0);
}
<input type="text" id="numbers-only" onpaste="myFunction(this);" >
With a event listener
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
I have input (type=password) and I restrict this input only for some characters. Code is here
$(document).ready(function() {
$('#nguestpass, #nguestps, #nuserpass, #nuserps, #nadminpass, #nadminps').bind('keyup').bind('keyup', function(){
new_char = $(this).val();
if (/[^a-zA-Z0-9\!\#\#\%\*\(\)_\-\+\=\[\]\:\;\'\,\.\?/]/.test( new_char ) === true ) {
alert('Entred character is not allowed. Please correct it.');
return false;
}
return true;
});
});
If I paste invalid code (example "ř") get alert (Entered....). It is correct. If I want to enter next characters I get alert again.
I think that is nasty for user. Better modification (according me) - if I entered invalid characters I get alert - confirm OK and invalid character will be remove.
Can any idea what do it? Thanks
P.s.: Sorry for my english.
Try this to remove the last character:
$(this).val($(this).val().substring(0,$(this).val().length-1));
and put this before your return false;
This should do what you're expecting:
$(function () { // Same as document ready, just shorter.
// Try to replace all these IDs with a common class you can put on every input.
// If you're using a not-so-old version of jQuery, use .on() instead of .bind().
$('#nguestpass, #nguestps, #nuserpass, #nuserps, #nadminpass, #nadminps').on('keyup', function () {
var new_char = $(this).val();
if (/[^a-zA-Z0-9\!\#\#\%\*\(\)_\-\+\=\[\]\:\;\'\,\.\?/]/.test(new_char) === true) {
alert('Entred character is not allowed. Please correct it.');
$(this).val(new_char.substring(0, new_char.length - 1));
return false;
}
return true;
});
});
Demo
There is quite a few mistake in your code (bind called once without listener, new_char is a global variable) and nothing to actually clear the invalid value which is what should happen when a password is wrong.
Try this.
$(function() {
$('#nguestpass, #nguestps, #nuserpass, #nuserps, #nadminpass, #nadminps').bind('keyup', function(){
var new_char = $(this).val();
if (/[^a-zA-Z0-9\!\#\#\%\*\(\)_\-\+\=\[\]\:\;\'\,\.\?/]/.test( new_char ) === true ) {
alert('Entred character is not allowed. Please correct it.');
// reset value
$(this).val("");
return false;
}
});
});
This is my jquery code that I am using to truncate the pasted text, so that it doesn't exceed the maxlength of an element. The default behaviour on Chrome is to check this automatically but in IE 8 and 9 it pastes the whole text and doesn't check the maxLength of an element. Please help me to do this. This is my first time asking a question here, so please let me know if I need to provide some more details. Thanks.
<script type="text/javascript">
//var lenGlobal;
var maxLength;
function doKeypress(control) {
maxLength = control.attributes["maxLength"].value;
value = control.value;
if (maxLength && value.length > maxLength - 1) {
event.returnValue = false;
maxLength = parseInt(maxLength);
}
}
//function doBeforePaste(control) {
//maxLength = control.attributes["maxLength"].value;
//if (maxLength) {
// event.returnValue = false;
//var v = control.value;
//lenGlobal = v.length;
// }
// }
$(document).on("focus","input[type=text],textarea",function(e){
var t = e.target;
maxLength = parseInt($(this).attr('maxLength'));
if(!$(t).data("EventListenerSet")){
//get length of field before paste
var keyup = function(){
$(this).data("lastLength",$(this).val().length);
};
$(t).data("lastLength", $(t).val().length);
//catch paste event
var paste = function(){
$(this).data("paste",1);//Opera 11.11+
};
//process modified data, if paste occured
var func = function(){
if($(this).data("paste")){
var dat = this.value.substr($(this).data("lastLength"));
//alert(this.value.substr($(this).data("lastLength")));
// alert(dat.substr(0,4));
$(this).data("paste",0);
//this.value = this.value.substr(0,$(this).data("lastLength"));
$(t).data("lastLength", $(t).val().length);
if (dat == ""){
this.value = $(t).val();
}
else
{
this.value = dat.substr(0,maxLength);
}
}
};
if(window.addEventListener) {
t.addEventListener('keyup', keyup, false);
t.addEventListener('paste', paste, false);
t.addEventListener('input', func, false);
} else{//IE
t.attachEvent('onkeyup', function() {keyup.call(t);});
t.attachEvent('onpaste', function() {paste.call(t);});
t.attachEvent('onpropertychange', function() {func.call(t);});
}
$(t).data("EventListenerSet",1);
}
});
</script>
You could do something like this, mind you this was done in YUI but something simlar can be done for jquery. All you need to do is get the length of the comment that was entered and then truncate the text down the the desired length which in the case of this example is 2000 characters.
comment_text_box.on('valuechange', function(e) {
//Get the comment the user input
var comment_text = e.currentTarget.get('value');
//Get the comment length
var comment_length = comment_text.length;
if(comment_length > 2000){
alert('The comment entered is ' + comment_length + ' characters long and will be truncated to 2000 characters.');
//Truncate the comment
var new_comment = comment_text.substring(0, 2000);
//Set the value of the textarea to truncated comment
e.currentTarget.set('value', new_comment);
}
});
You're putting too much effort into something that is apparently a browser quirk and is mostly beyond your control and could change in the future. In fact, I can't recreate this in IE10 - it behaves just like Chrome for me.
Make sure you are validating the length on the server-side, since it's still possible to get around a field's maxlength when submitting the form input to the server (see this somewhat similar question). That's not to say you shouldn't have some client-side logic to validate the length of the input to enforce the maxlength constraint - I just think you don't need to go to the length you are attempting here to essentially intercept a paste command. Keep it simple - having a basic length validation check in your JavaScript is going to be a lot less messy than what you have here.
Perhaps consider a bit of jQuery like this:
$("#myTextControl").change(function() {
if ($(this).val().length > $(this).attr('maxlength')) {
DisplayLengthError();
}
});
(where DisplayLengthError() is an arbitrary function that triggers some kind of feedback to the user that they have exceeded the maxlength constraint of the field, be it an error label, and alert box, etc.)
I hope this isn't a daft question. I expected google to be promising but I failed today.
I have a textbox <input type="text" id="input1" /> that I only want to accept the input /^\d+(\.\d{1,2})?$/. I want to bind something to the keydown event and ignore invalid keys but charCode isn't robust enough. Is there a good jQuery plugin that does this?
The affect I want to achieve is for some one to type 'hello world! 12.345' and want all characters to be ignored except '12.34' and the textbox to read '12.34'. Hope this is clear.
Thanks.
I don't think you need a plugin to do this; you could easily attach an event and write a simple callback to do it yourself like so:
$('#input1').keyup(function()
{
// If this.value hits a match with your regex, replace the current
// value with a sanitized value
});
try this:
$('#input1').change(function(){
if($(this).data('prevText') == undefined){
$(this).data('prevText', '');
}
if(!isNaN($(this).val())){
$(this).val($(this).data('prevText'))
}
else {
//now do your regex to check the number settings
$(this).data('prevText', $(this).val());
}
})
the isNAN function checks to make sure the value is a number
$('#input1').bind('keyup', function() {
var val = $(this).val();
if(!val)
return;
var match = val.match(/^\d+(\.\d{1,2})?$/);
if(!match)
return;
//replace the value of the box, or do whatever you want to do with it
$(this).val(match[0]);
});
jQuery Keyfilter
Usage:
$('#ggg').keyfilter(/[\dA-F]/);
It also supports some pre-made filters that you can assign as a css class.
You should look at jQuery validation. You can define your own checking methods like this here.
$('input1').keyup(function(){
var val = $(this).val().match(/\d+([.]\d{1,2})?/);
val = val == null || val.length == 0 ? "" : val[0];
$(this).val(val);
});
I found the solution.
Cache the last valid input on keydown event
Rollback to last valid input on keyup event if invalid input detected
Thus:
var cache = {};
$(function() {
$("input[regex]").bind("keydown", function() {
var regex = new RegExp($(this).attr("regex"));
if (regex.test($(this).val())) {
cache[$(this).attr("id")] = $(this).val();
}
});
$("input[regex]").bind("keyup", function() {
var regex = new RegExp($(this).attr("regex"));
if (!regex.test($(this).val())) {
$(this).val(cache[$(this).attr("id")]);
}
});
});