jQuery replace invalid character - javascript

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;
}
});
});

Related

jQuery - find text in textarea

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/

How to make an input restriction function using jquery

I want to do is put a character and length restriction in an input using this rules:
A combination of at least ten numbers, letters and punctuation marks
(like ! and &)
and if the user didnt complete the rules the input value will be back to empty again.
My problem is I'm still a beginner and my current code wont work as i wanted. Can anyone help me with this please.
Current output: http://jsfiddle.net/5kcsn/271/
Script:
$(document).ready(function () {
$('#example').on('blur', function () {
$('#example').change(inputVerify);
inputVerify()
})
$('#example').on('keydown', function () {
$('#example').change(inputVerify);
inputVerify()
})
$('#example').change(inputVerify);
function inputVerify(value) {
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value) && /[a-z]/.test(value) && /\d/.test(value)
};
});
I don't want to tell you "how to do it better in general", but what about giving live feedback instead of reverting a bad entry? This way the user can a) see as soon as it is correct, b) correct his former entry:
$("#example").on('keydown',function(){
if(!inputVerify($("#example").val())){
$("#example").css("border","1px solid red");
} else {
$("#example").css("border","1px solid black");
}
});
function inputVerify(value){
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value)
};
You should really do this only on blur, it should look something like this:
$(document).ready(function(){
$('#example').on('blur', function(){
if( !inputVerify() ) {
$(this).val('');
}
});
});
function inputVerify(value){
return /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value)
};
You see, your inputVerify function returns true or false and you would have to remove the input yourself by $(this).val('');.
The jsFiddle: http://jsfiddle.net/5kcsn/272/
Please note that I have not tested your regex, as I am not too familiar with them, yours seem to work though.
Try this, note I did not check your regular expression:
$(document).ready(function () {
$('#example').keydown(inputVerify);
function inputVerify(event) {
var value = $(this).val();
if (!(/^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{10,20}$/.test(value)
&& /[a-z]/.test(value)
&& /\d/.test(value))) {
$(this).val('');
}
};
});
Link to JSFiddle
The function inputVerify catches the event passed by the keydown handler and uses the $(this) which refers to the element the event is triggered on to get the value of the input.
And then, if the regex tests fail, empty the input.

how to validate a textarea using javascript

I want to check a textarea whether it is empty or not. For this I write the following code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}​
For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?
I am getting it correctly. This is what I did.
Click on validate, it said Please Write Problem Description.
Write something and click. Nothing happened.
Remove the text. Click on validate, it said Please Write Problem Description.
Note: Use a trim function to eliminate empty spaces.
Code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Demo: http://jsfiddle.net/TZGPM/1/ (Checks for Whitespaces too!)
Do check for white space in the value like this
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute.
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value.replace(/ /g,'').length) {
return true;
} else {
alert("Please Write Problem Description");
return false;
}
}
<textarea id="problem_desc"></textarea>
<button onclick="validateForm()">Validate</button>

JS filter textbox input

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")]);
}
});
});

jquery / JS allow only numbers & letters in a textfield

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.

Categories

Resources