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.
JavaScript onKeypress validation - Code Review Stack Exchange
javascript - Input validation in the keydown event - Stack Overflow
html - How do I detect keypresses in Javascript? - Stack Overflow
javascript - Number validate at keypress - Stack Overflow
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
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;
}
With plain Javascript, the simplest is:
document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};
But with this, you can only bind one handler for the event.
In addition, you could use the following to be able to potentially bind multiple handlers to the same event:
addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.
References:
- https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
- https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
With jQuery:
$(document).on("keypress", function (e) {
// use e.which
});
Reference:
- http://api.jquery.com/on/
Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.
Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown
As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.
Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.
Here's something that might help decide:
- http://www.jscripters.com/jquery-disadvantages-and-advantages/
NOTE: JS's keypress is deprecated:
https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
The jQuery solutions in this answer may still be relevant.
KEYPRESS (enter key)
Click inside the snippet and press Enter key.
Vanilla
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('hi.');
}
});
Vanilla shorthand (Arrow Function, ES6)
this.addEventListener('keypress', event => {
if (event.keyCode == 13) {
alert('hi.')
}
})
jQuery
$(this).on('keypress', function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery classic
$(this).keypress(function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery shorthand (Arrow Function, ES6)
$(this).keypress((e) => {
if (e.keyCode == 13)
alert('hi.')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Even shorter (ES6, ECMAScript 2021)
$(this).keypress(e=>
e.which==13&&alert``
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Due to some requests, here is an explanation:
I rewrote this answer as things have become deprecated over time so I updated it. Just for info, it is not about "keydown", it's about "keypress". So some non-character keys like "Esc" aren't supposed to work like that but I'll explain.
I used this to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.
Deprecated:
The .which and .keyCode methods are actually considered deprecated so I would recommend .code but I personally still use keyCode as the performance is much faster and only that counts for me.
The jQuery classic version .keypress() is not officially deprecated as some people say but they are no more preferred like .on('keypress') as it has a lot more functionality(live state, multiple handlers, etc.).
The 'keypress' event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown, keyup today.
Performance:
The faster the better. This is why I prefer .keyCode even if it's considered deprecated(in most cases). It's all up to you though (Commited 2020).
Performance Test
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();
}
});
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 :)
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);
Keep it simple. Use both onKeyPress() and onKeyUp():
<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()">
This takes care of getting the most updated string value (after key up) and also updates if the user holds down a key.
jsfiddle: http://jsfiddle.net/VDd6C/8/
Handling the input event is a consistent solution: it is supported for textarea and input elements in all contemporary browsers and it fires exactly when you need it:
function edValueKeyPress() {
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The text box contains: " + s;
}
<input id="edValue" type="text" onInput="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>
I'd rewrite this a bit, though:
function showCurrentValue(event)
{
const value = event.target.value;
document.getElementById("label").innerText = value;
}
<input type="text" onInput="showCurrentValue(event)"><br>
The text box contains: <span id="label"></span>