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.
Related
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;
}
});
});
I'd like to start an action (enabling autocomplete) when user types '#'. I have jQuery available.
Usually on a QWERTY keyboard, it is like this:
$('textarea').live('keydown', function(e) {
if (e.which === 50) {
console.log('# has been entered.');
}
});
However it does not work correctly on an AZERTY keyboard. The keyCode = 50 corresponds to the é~/2 key. To type '#' in AZERTY keyboard, it is AltGr + à#/0 key.
Edit: Autocomplete starts when # is entered, and only after that. Example, when someone enters "Hello #" then it starts, however when he types "Hello #nothing else" the complete won't do anything. Example: http://mrkipling.github.com/jQuery-at-username/ (it works only on QWERTY keyboard).
Use keypress instead of keydown. While keydown relates to every press of a key, keypress relates to the translated characters, so for example a can be different to a while the shift key is pressed, composed characters work, dead-keys work, and other differences in keyboard mappings are handled.
How about checking if # was entered as the last character in the field value?
$("body").on("keyup", "textarea", function(e) {
if (this.value.indexOf("#") == this.value.length - 1) {
console.log("Starting autocomplete");
}
});
DEMO: http://jsfiddle.net/FKhPW/2/
Use event.key and modern JS, checking for # directly!
No number codes anymore. You can check key directly.
const input = document.getElementById("textarea");
input.addEventListener("keydown", function (event) {
if (event.key === "#") {
// Do something
}
});
Mozilla Docs
Supported Browsers
The only other option that comes to mind would be a timer that checks the content of the text input.
var patt=new RegExp(/^#/);
var charCheck = setInterval(function(){
if (patt.test($("#textInput").val())){
// initiate autocomplete
}
},100);
This code will inspect the contents of the #textInput element and see if it matches the regular expression of a # symbol at the beginning of the string. If it does, the test() function will evaluate to true and you can initiate your autocomplete code.
Here you go working demo: http://jsfiddle.net/LxpQQ/
From my old reply here:
jquery autocomplete using '#'
Hope it will fit you cause :)
code
source: function(request, response) {
if (request.term.indexOf("#") >= 0) {
$("#loading").show();
getTags(extractLast(request.term), function(data) {
response($.map(data.tags, function(el) {
return {
value: el.name,
count: el.count
}
}));
$("#loading").hide();
});
}
},
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")]);
}
});
});
I thought it would be a simple thing to hijack the space key when in a form input so that it would function like a hyphen. Generally jQuery makes stuff like this really simple.
The code I tried is this:
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) return 109;
});
But this has no effect whatsoever. I tried a more simple script:
$("#StreamUrl").keydown(function (e) {
//if (e.keyCode == 32) return 109;
alert(e.keyCode);
});
This script correctly alerts 32 on space press and 109 on hyphen press. Also, I have no JavaScript errors.
Why wouldn't if (e.keyCode == 32) return 109; work? When I replace that line with if (e.keyCode == 32) alert("space!!"); I get the alert correctly, so I know the if is returning true correctly.
What gives?
Edit - Solution
Thanks to #Nick for pointing out the copy-paste issue. I ended up with a little bit of a hybrid. Here's the code that I have gotten to work which is both smooth and handles Copy/Paste.
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) {
$(this).val($(this).val() + "-"); // append '-' to input
return false; // return false to prevent space from being added
}
}).change(function (e) {
$(this).val(function (i, v) { return v.replace(/ /g, "-"); });
});
The problem is that return 109 doesn't do what you want it to do. In an event handler, you return true or false depending on whether or not you want the browser to execute the default action. In keydown, you would return false to prevent the character from being inserted.
$("#StreamUrl").keydown(function (e) {
if (e.keyCode == 32) {
$(this).val($(this).val() + "-"); // append '-' to input
return false; // return false to prevent space from being added
}
});
jsfiddle example
You usually want the keyup event instead here, which fires after the space has been added, something like this is a bit easier:
$("#StreamUrl").bind("keyup change", function () {
$(this).val(function(i, v) { return v.replace(/ /g,"-"); });
});
Try it out here, what this does is allow the space to be added, but then instantly does a replace of spaces for hyphens by passing a function to .val(). For older versions of jQuery, it'd look like this:
$("#StreamUrl").bind("keyup change", function () {
$(this).val($(this).val().replace(/ /g,"-"));
});
This works even for people pasting content, an easy way to get around keydown validation.
How to check for a comma in a text box? I.e. if comma is present the code should alert,
<input type="text" id="name"/>
You could do like:
if ($('#name').val().indexOf(',') !== -1)
{
alert('There was a comma');
}
As you have not specified, you could put that code in blur event, etc.
$("#name").blur(function() { // or keyup, keydown, keypress, whatever you need
if(this.value.indexOf(",") !== -1) {
alert('got a comma');
}
});
Doesn't really need jQuery (for the test). Here's a regular expression test().
if( /\,/.test( $('#name').val() ) ) {
alert('found a comma');
}
A regular expression test() function returns true or false.
And the obligatory no-jQuery solution ;)
if (document.getElementById("name").value.indexOf(",") !== -1) {
....
}