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);
Answer from insert_name_here on Stack OverflowYou 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);
validation - jquery - validate characters on keypress? - Stack Overflow
How do I validate a form element on key press?
Javascript validation onkeypress function - Stack Overflow
JavaScript onKeypress validation - Code Review Stack Exchange
$('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
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.
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.
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 just want to validate the textbox for required use HTML5 required attribute like:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>
Validate on blur, or on submit. Don't validate while typing, for exactly the reason you describe.
There are studies/observations that show the people generally complete the entire form and then return to values that are incorrect. Even if you validate on blur they will tend to complete all fields and will then return to fix.
Article: Usable error message presentation in the World Wide Web: Do not show error right away Author: Javier A. Bargas-Avila, Glenn Oberholzer, Peter Schmutz, Marco de Vito, and Klaus Opwis Source: Interactive with Computers, Volume 19, pages 330-341 (2007)
Results of the Study
- When Completing an online form users have two modes: Completion Mode and Revision Mode
- Users tend to ignore immediate error messages when they are in Completion Mode
- Of the size possible ways to present error messages, three proved to be more effective than the others:
- Present the error afterward, embedded in the form, all at once
- Present the error afterward, embedded in the form, one by one
- Present the error afterward, in dialogues, one by one
The study alone suggests you should present error after the user has completed the form -- in other words, on submit.
If you validate on blur, show a simple non-obtrusive error (a highlight and possible a short message next to or under the field). Do not force the user to fix it immediately. You can disable the "submit" button until all fields are validated -- include a small message or popover indicating why the "submit" button is disabled (e.g., "Please fix the highlighted fields before submitting"). You can let the user submit despite errors too and display an additional error message then.
Note that you have to validate on submit if you want make sure you catch errors. Client side validation (i.e., on blur) requires JavaScript and JavaScript can be turned off. It is rare these days, but it is not unheard of. Also, not all browsers support the same level of JavaScript.
Validating on blur helps the user realize something is wrong before they submit, but you will also need to validate on submit to make absolutely sure everything is formatted the way you want it. However, the study quoted above would suggest that validating on blur does not buy you anything that validating on submit already provides.
As revealed in this fantastic article, the answer is on blur.
To quote:
When we used the “after” method in the first half of the form, participants completed the form seven to ten seconds faster than when we used the “while” and “before and while” methods respectively. Why? Here’s what happened when we used the “while” and “before and while” methods: When several participants noticed an error message while trying to answer a question, they entered one additional character into the input field, than waited for the message to update. If the updated message continued to show an error, they entered another character, then waited for the validation message to update again, and so on, resulting in longer average completion times.
The “before and while” method not only caused longer completion times, but also produced higher error rates and worse satisfaction ratings than the other inline validation variations we tested. Our participants articulated their strong distaste for this methodology:
“It’s frustrating that you don’t get the chance to put anything in [the field] before it’s flashing red at you.”
“When I clicked in the First Name field, it immediately came up saying that [my first name] is too short. Well of course it is! I haven’t even started!”
“I found it quite annoying how red crosses came up when you hadn’t finished typing. It’s just really distracting.”
These negative reactions, longer completion times, and error rates illustrate that validating inputs prematurely can be harmful. Instead, when you validate open-ended questions, give feedback after the user finishes providing an answer. Or in situations in which people need help sooner, give feedback while they work toward an answer, but use an appropriate delay so premature error messages don’t frustrate them.
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();
}
});
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/