I have this great piece of code that only allows letters in a form, however, it waits for you type the number and then gives it a null value (i think). If I wanted it to totally block any number keys (etc), how would I change it? AND, is there a way I could do this to only allow numbers???
function validLetters(f)
{
!/^[A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ]*$/i.test(f.value)?f.value = f.value.replace(/[^A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ]/ig,''):null;
}
This code below totally blocks letters and signs! How would I apply that to the top code???????????
function validNumbers(myfield, e, dec)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}
My question to you is WHEN do you want to perform the check?
I think preventing people to type anything you don't want ( like numbers ) can be done either onKeyPress or Onsubmit, where onsubmit check the values already entered ofc.
First of all, you have to consider characters like Á are not typed with only one key. You use a combination depending on your keyboard configuration. Therefore using onkeyup is with the keyCode is not a good idea, since you will limit what the user can type to plain letters and numbers w/o special characters like É.
This code is the best you can get:
Code:
function validLetters(f)
{
!/^[A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ]*$/i.test(f.value)?f.value = f.value.replace(/[^A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ]/ig,''):null;
}
As it simply removes unallowed characters after the user types it.
Now, what I recommend is letting the user type anything he wants but warn him against any disallowed characters via an error message either on top, at the side or below the input element. Its just easier because it allows combination of keys to type in characters like Á.
Use the keyCode method when you really only want basic letters, number or a combination of both and/or characters that can be type readily with one key stroke.
if (!/^[A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ]+$/gi.test(THE STRING)) {
alert("Enter only letters or die");
}
[A-zÇÑQÀÁÈÉÍÌÏÓÒÚÙÜ] That means nothing, you need the //, and then ^ for the start, + for one or more, and $ for end.
Great wit and madness are near allied, and fine a line their bounds divide.
Bookmarks