There are a couple of libraries that you could use. If you want to stick to pure JavaScript without any jQuery, then your best option would probably be Validate JS.
There are a ton of jQuery options if you are willing to work with jQuery - these are usually more feature packed and nicer to look at too. You could also use the Validator built into the Foundation Framework - it's called Abide but it uses jQuery.
Hope this helps.
Answer from Nischaal Cooray on Stack OverflowThere are a couple of libraries that you could use. If you want to stick to pure JavaScript without any jQuery, then your best option would probably be Validate JS.
There are a ton of jQuery options if you are willing to work with jQuery - these are usually more feature packed and nicer to look at too. You could also use the Validator built into the Foundation Framework - it's called Abide but it uses jQuery.
Hope this helps.
This may or may not be the answer you are looking for, but perhaps you should be looking at a solution that requires less JavaScript:
In HTML 5, you can specify the type of value that an input is supposed to accept using a pattern, you can read about this on this mozilla page or by reading the answers on this question: HTML5 Form Pattern / Validation.
<input type="text" name="country_code" pattern="put a regex here that describes only valid input for your situations" title="Three letter country code">
Note that not all browsers (primarily Safari and older IE) currently support the pattern attribute.
Another thing of note is that it may be preferable to use a RegEx in your JavaScript code, should that be the preferred solution.
You can make your function run when the keypress event is fired with:
$("#purpose").on('keypress', validate);
However, using the keypress event on a text input is generally a bad idea. It doesn't work on mobile devices, and it doesn't trigger when Backspace or Delete is pressed or text is pasted or cut in or out of the input. You should probably use the input event instead:
$("#purpose").on('input', validate);
$('#purpose').keyup(validate);
onKeyValidateis an okay name, but a better name could bevalidateKeypress.It seems very silly to store a RegExp as a string, and then construct it every time. Why not just declare
var alpha = /[ A-Za-z]/?keyCharsappears to check against\x00, the null character, and\x08, the backspace character. Neither of these can ever be passed toonKeypress, so you can just take it out.The standard way to get the character code is
event.which || event.keyCode.eventis a global; I don't think you need to pass it in.
Here's a proposed rewrite:
var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/;
var alphanumeric = /[ A-Za-z0-9]/;
function validateKeypress(validChars) {
var keyChar = String.fromCharCode(event.which || event.keyCode);
return validChars.test(keyChar) ? keyChar : false;
}
The HTML will have to change to onkeypress="validateKeypress(alpha);".
The thing that I was able to pick out, and it's more of a nitpick type of things is that you should turn your last if statement around
if (!validChars.test(keychar) && !keyChars.test(keychar)) {
return false
} else{
return keychar;
}
should look like this
if (validChars.test(keychar) && keyChars.test(keychar)) {
return keychar;
} else {
return false;
}
Do your Positive first. most people like this better than all the negatives.
Side Note: for code golfing you just shaved 2 characters as well as made it more standard compliant if this nitpick can be considered a standard.
Short Version:
If you know Ternary operators and would like to use them instead of this simple if statement, @renatargh mentioned that you could make this super short
return validChars.test(keychar) && keyChars.test(keychar) ? keychar : false;
Also, var alphanumeric = "[ A-Za-z0-9]"; is never used (in this code block) and neither is
var keyChars = /[\x00\x08]/;
you should just get rid of them
You shouldn't exclusively use onkeyup or onkeydown for detecting user input. They don't catch the edge cases such as cut, paste, drag and drop or spell checker corrections. You should use the HTML 5 event, oninput where available (Firefox 2+, Google Chrome, Safari 4+, Opera 10) and Internet Explorer's onpropertychange event. For browsers that don't support either event, you can fall back to onkeydown with a 0ms timer for the check, which is a little better than onkeyup.
In newer browsers, you can check for the oninput event, which should be the most reliable approach.
I'm guessing "when the last keypress is up" means when the two password fields contain values of the same length? If so, then have the keyup event listener first check the length of the values. For example, don't try to validate until the 2nd password length is equal or longer than the length of the 1st password. Of course, if the 2nd is longer than the first, it fails validation :)
The first character is unrestricted because you have nested keypress handlers. Try this:
$('.Number').keypress(function (event) {
var keycode = event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
Try
$('.Number').keyup(function (event) {
var keycode = event.which;
if (!(event.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
event.preventDefault();
}
});
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; } ) );
});
EDIT:
There are some other good answers here that will prevent the input from taking place.
I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an alert to show the error.
http://jsfiddle.net/ntywf/2/
Well the patrick's answer removes character if it is wrong, to actually prevent character from being inserted into the field use
$("#field").keypress(function(e) {
// Check if the value of the input is valid
if (!valid)
e.preventDefault();
});
This way the letter will not come to textarea
If you're checking a printable key, which is exactly what you seem to be doing, you should use the keypress event instead, since that's the only place you're going to be able to get reliable information about the character the keypress represents. You can't detect numeric keypresses reliably in the keydown event. Also, it's a bad idea to suppress arrow keys and delete/backspace keys. What do you gain from doing that?
There's also some errors: in Firefox, you'll need to get the Event object from the parameter passed into the event handler function, and if you're using a DOM0 event handler function rather than addEventListener() or attachEvent(), you should use return false; to suppress default behaviour. Here's my recommended code:
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/\d/.test(charStr)) {
return false;
}
};
I don't think you need the preventDefault part. If you want to catch keys (by event.keyCode, or combinations using for example event.ctrlKey + event.keyCode), you check if the keyCode is allowed. If it is, simply return true, otherwise return false. If you return false, the key input will not be written to the input field, otherwise it will.
I can't think of better ways to then using keyCode. You can use String.fromCharCode([keyCode]) if you want to check for specific character values, but it keeps boiling down to some loop to check the keyCodes you want to validate. May be a switch ... case could offer a bit more readability.
Here's a piece of code from a keydown event handler I use (just for demonstration, it doesn't actually do anything):
function handleKey(e, thisFld) {
thisFld = (thisFld || this);
e = e || event;
if (!e) {
return true;
}
var isCtrl = e.ctrlKey,
isShift = e.shiftKey,
isAlt = e.altKey,
kc = e.keyCode || e.which,
codes = [27, 38, 40],
keys = {
escape: 27,
up: 38,
down: 40,
ins: 45,
del: 46,
one: 49
};
if (isCtrl && kc === keys.del) { ... }
if (isAlt && kc === keys.ins) { ... }
//etc
return true;
}
Use keypress event. Try with this -
onkeypress="alert(/([A-Z0-9a-z_-][^@])+?@[^$#<>?]+?\.[\w]{2,4}/.test(this.value))"
I would prefer to use onblur in this case.
You can also use jquery -
HTML
<input id="email_address">
<span id="error" style="display:none;color:red;">Wrong email</span>
Jquery
$('#email_address').on('keypress', function() {
var re = /([A-Z0-9a-z_-][^@])+?@[^$#<>?]+?\.[\w]{2,4}/.test(this.value);
if(!re) {
$('#error').show();
} else {
$('#error').hide();
}
})
DEMO
Try this...
<input type="text" class="keyup-email text-input" name="7" value="">
$(document).ready(function(){
$('.keyup-email').keyup(function() {
$('span.error-keyup-7').remove();
var inputVal = $(this).val();
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputVal)) {
$(this).after('<span class="error error-keyup-7">Invalid Email Format.</span>');
}
});
});
fiddle:http://jsfiddle.net/091ep28h/3/