I want to write a validation for a textarea to prevent to type some words, well for example if you type Viber on textarea it will remove that and then alert, my problem is this code only work when you type viber first! if you type for ex: I like Viber, it doesn't work, i want to find viber everywhere in textarea and remove it, and second problem is i want to do this with all type of text in lowercase and uppercase, VIBER, viber, Viber, ViBeR and etc... can i do this?
$('textarea').keyup(function() {
var val = this.value;
var my = $(this).val();
if ( val.indexOf('viber') == 0 ) {
$(this).val($(this).val().split(my).join(""));
alert("viber not allowed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea></textarea>
JSFiddle
$('textarea').keyup(function() {
if ($(this).val().toLowerCase().indexOf('viber') != -1) {
$(this).val($(this).val().replace(/viber/i, ''));
alert('never say "Viber" again!');
}
});
And pay attention to the String.indexOf - it returns index of the first match or -1 if it didn't find anything. In your case, you're checking for zero - it's wrong because zero means that it finds first occurence in the begginning of string.
$('textarea').keyup(function() {
var val = this.value.toLowerCase();
var my = $(this).val();
if ( val.indexOf('viber') != -1 ) {
$(this).val($(this).val().split(my).join(""));
alert("viber not allowed");
}
});
http://jsfiddle.net/0g5kxbbh/2/
Related
I'm trying to remove a character as it's typed/keyed up to test whether it's a number or not, if it is a number, keep it, if not, remove it. It can be more than one digit. for example, I type in a "d", it should be deleted from the textbox. I then type a "1", where it should stay in the textbox. I then type a 4 and it also stays so the textbox now reads "14". Then I type "g", which should be deleted. Then I type a "5" and now the text box reads 145. This is what I have so far.
$("#txtTestNumbersOnlyRegex").keyup(function () {
$("#txtTestNumbersOnlyRegex").val(function (index, value) {
var keyPressed = value.substr(0, value.length - 1);
var regEx = new RegExp("/^5$/");
if(!regEx.test(keyPressed)) {
alert("true");
return value.substr(0, value.length - 1);
}
});
});
You might want to try this:
$("#txtTestNumbersOnlyRegex").keyup(function () {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
You can try it here https://fiddle.jshell.net/aooh0gkz/
You can use regex to replace any non digits with empty space, although this will look a bit weird.
$('input').keyup(function() {
$(this).val($(this).val().replace(/\D/, ''));
});
Full snippet:
$('input').keydown(function() {
console.log($(this).val());
$(this).val($(this).val().replace(/\D/, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Or you could use input type="number" if you don't care about IE support.
You can intercept the values that are coming in and decide what to do, So it is better to have the keypress else your text gets replaced everytime and say if you are in middle of input val and you are editing caret will jump to the end in other cases
$("#txtTestNumbersOnlyRegex").keypress(function (event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if((keyCode>=65 && keyCode<=90) || (keyCode>=97 && keyCode<=122))
return false;
else return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id = txtTestNumbersOnlyRegex />
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;
}
});
});
$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?
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")]);
}
});
});
So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.