Working Jsfiddle
I would prefer without regex:
function validate() {
var num = document.getElementById("points2").value;
var num = parseInt(num, 10);
alert(num);
if (num < 5 || num > 10) {
document.getElementById("points2").value = "";
alert("Please Enter only between 5 and 10 ");
}
}
change your regex to :
/^([5-9]|10)$/
you should use onchange event:
<input type="text" id = "points" onchange="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^([5-9]|10)$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}
Answer from Zaheer Ahmed on Stack OverflowWorking Jsfiddle
I would prefer without regex:
function validate() {
var num = document.getElementById("points2").value;
var num = parseInt(num, 10);
alert(num);
if (num < 5 || num > 10) {
document.getElementById("points2").value = "";
alert("Please Enter only between 5 and 10 ");
}
}
change your regex to :
/^([5-9]|10)$/
you should use onchange event:
<input type="text" id = "points" onchange="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^([5-9]|10)$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}
$('#textbox').keyup(function() {
var value = $('#textbox').val();
if(value != ''){
if(!value.match(/^[5678910]$/))
textboxError();
else{
var length = value.length;
if(value.charAt(length-1) == 0 && value.charAt(length-2) != 1)
textboxError();
}
}
};
$('#textbox').change(function() {
var value = $('#textbox').val();
if(value != '')
textboxError();
}
};
function textboxError(){
$('#textbox').val('');
$('#textbox').focus();
alert("Please Enter only between 5 and 10 ");
}
What we are doing is,
- Check if value is empty (If empty don't perform anything)
- If not empty check if the value matches to defined set
- If it match, now we do check for 10. What we do is if last entered item of field is 0, than the previous field must be 1 so it makes a 10. If not we throw error.
- But here is a problem, the user might enter 1 and leave the field without entering another char. So, u can extend this by onchange field.
- Onchange, now we check for count of 1 and that should match count of 10. It fixes our problem. You don't have to worry of 0 because we already check it in keyup block.
I Didn't check the code. So if any typos or errors, u can replace them.
validating on keyup
jQuery.validate.js onkeyup = true error - Stack Overflow
javascript - Validation on onKeyUp - Stack Overflow
Field validation with JavaScript - onkeyup? - Stack Overflow
You actually need to set the onkeyup option to a function that accepts the element being validated as a parameter, so try changing:
onkeyup: true,
to
onkeyup: function(element) {$(element).valid()}
onkeyup is enabled by default so you do not need to set it to true. If you do, you break the functionality already built into the plugin.
You have three options:
1) Leave the onkeyup option out of .validate(). This keeps onkeyup functionality enabled by default. (edit: "by default" means that validation occurs on every "key-up" event only after the field is initially validated by another event.)
DEMO: http://jsfiddle.net/ZvvTa/
2) onkeyup can be set to false to disable this option.
DEMO: http://jsfiddle.net/ZvvTa/1/
3) Replace onkeyup with your own callback function to modify how it operates. (Demo uses default function)
DEMO: http://jsfiddle.net/ZvvTa/2/
Below is the default, unmodified, onkeyup callback function:
onkeyup: function( element, event ) {
if ( event.which === 9 && this.elementValue(element) === "" ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element(element);
}
}
See: http://docs.jquery.com/Plugins/Validation/validate#toptions
EDIT:
By default, the plugin does not do any "key-up" validation until after the field is initially validated by another event. ("Lazy" validation)
So here is a more properly modified version of the onkeyup callback function that will provide immediate onkeyup validation. ("Eager" validation)
DEMO: http://jsfiddle.net/QfKk7/
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
}
Working DEMO
You need to escape back slash (\) so your regular expression should be ^\\d{3,4}$ instead ^(d){3,4}$
You need to add a \ in front of the d, without it the d is represented as the character d and not a numeric value. Here's the expression you should use ^\d{3,4}$.
EDIT
The first part was on track, but I missed that you were passing the pattern as a string to another function. If you were to run new RegExp('^\d{3,4}$', "") it would work, but because it was being passed through a function, the \ character was being removed. In order to pass a string with a backslash in it, you need to escape the slash with another back slash like so \\. This means your new expression should be ^\\d{3,4}$.
When developing regular expression I usually use something like http://regexpal.com/ to help test them. Keep in mind that for this one you would have to check the ^$ match at line breaks (m) box for it to match multiple tests on multiple lines
There are a few weird things going on here.
- You don't want to use the
onkeyupattributes of HTML elements. Bind an event listener function, which keeps your code more modular. - Like others said, you can't use the subtraction operator like that.
You probably don't want to alert every time someone types an invalid character. That will only annoy and anger a user. I am just logging it to the console, but you should think about putting the error text next to the input element.
$(function () { function ei(e) { var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?"; for (var i = 0; i < this.value.length; i++) { if (iChars.indexOf(this.value.charAt(i)) != -1) { console.log("Please do not use special characters."); this.value = this.value.slice(0, this.value.length - 1); this.focus(); return false; } } } $('#hurp').on('keyup', ei); });
And add an id to your input element:
<input type="text" name="name" id="hurp">ββββββββββββββββββββββββββββββββββ
See this JSFiddle: http://jsfiddle.net/QgLcB/
Why would you bother using the keyup event? It'd be better off using the keydown or keypress event and then cancelling it (I used this site to find the keycodes):
function ei (event) {
event = event || window.event;
switch (event.keyCode) {
case 47: //.
case 33: //!
//etc
event.preventDefault(); //cancel the current action, which will stop it writing out to the textbox
break;
default:
break;
}
}
I would also suggest you look into jQuery rather than having inline JavaScript to hook up your events and also take a look at the jQuery Validation plugin as that should help take care of a lot of your code.
Seriously, use jQuery validation to check for empties. They have done a very good job with validation.
<style>
.error { color: red; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$(document).ready(function() {
// validate signup form on keyup and submit
$("#omfg").validate({
rules: {
omfgdood: "required"
},
messages: {
omfgdood: "Oy! It\'s Empty!"
}
});
});
</script>
<?php $sk['chat']['recipient']['id'] = 'omfgdood'; ?>
<form id="omfg">
<textarea class="auto-grow-input" id="<?php echo $sk['chat']['recipient']['id']; ?>" name="<?php echo $sk['chat']['recipient']['id']; ?>"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
I think you can write your SK_sendChatMessage function like below.
function SK_sendChatMessage(text,recipient_id,e) {
document.title = document_title;
textarea_wrapper = $('.chat-textarea');
chat_messages_wrapper = $('.chat-messages');
if (e.keyCode == 13 && e.shiftKey == 0 && text == '') {
alert('enter text');
}
else{
textarea_wrapper.find('textarea').val('');
chat_messages_wrapper.append('<div class="chat-text align-right temp-text" align="right"><div class="text-wrapper float-right">' + text + '<div class="marker-out"><div class="marker-in"></div></div></div><div class="float-clear"></div></div>');
$.post(SK_source() + '?t=chat&a=send_message', {text: text, recipient_id: recipient_id}, function (data) {
chat_messages_wrapper
.append(data.html)
.scrollTop(chat_messages_wrapper.prop('scrollHeight'))
.find('.temp-text')
.remove();
});
}
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 :)
onKeyUp would result in the validation routines running after every key press. This could be viable if using a setTimeout as mentioned by @APAD1, but depending on the time, the user could leave the field before the validation routine, and depending on the form have submitted before the validation routine. This can also be very heavy. I would generally only use onKeyUp if you can validate the individual key press and swallow it. If you are waiting for final input to validate, then use onChange or onBlur.
onChange works for any field that would be picked up by the $(":input") selector (e.g. radios, selects, SLEs, etc). This is useful if you want to validate when they leave, but will only work if you re-focus the field and clear the bad contents. Else they could just ignore the error and keep going. If they never re-change the contents, the validation won't fire.
onBlur is very good if you want to validate as soon as input is complete and the field loses focus. I caution using this, depending on how you are notifying the user of the error. If you are alerting or doing something like re-focusing the field, then you can create a bad, blocking user experience.
As a general thought process, it is good to do instant validation on inputs, but inform the user in a non-blocking way (e.g. pop a div next to the field or something). ALWAYS preform a final validation of the entire form before sending information, as in some cases it could be possible for the user to ignore the validation messages, and subsequently send bad information.
onChange only works on certain types of elements (<SELECT> for e.g.).
onKeyUp will evaluate with every keypress, which is "heavy"
blur() is perhaps better because it is triggered each time you leave a field. But what about when you are still in the field and click the submit button?
Therefore, onsubmit is the best solution -- or a combination of the two. There is no problem with evaluating different ways for different fields, and validating again after clicking submit
From this answer it tells that Firefox doesn't take innerText or innerHTML to set a value, rather it takes textContent to set a value. So use textContent to set your value if the browser is Firefox
DEMO
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
var f=navigator.userAgent.search("Firefox"); //check if browser if FF
if(f>-1)
document.getElementById("mylocation").textContent=msg //if yes use this
else
document.getElementById("mylocation").innerText=msg //else normal approach
}
Note :- As I suggested in comment use
onkeypressinstead ofonkeyupfor keypressandholdevents validation.DEMO
To identify different browsers you can use below code from this answer
function checkBrowser(){
c=navigator.userAgent.search("Chrome");
f=navigator.userAgent.search("Firefox");
m8=navigator.userAgent.search("MSIE 8.0");
m9=navigator.userAgent.search("MSIE 9.0");
if (c>-1){
brwsr = "Chrome";
}
else if(f>-1){
brwsr = "Firefox";
}else if (m9>-1){
brwsr ="MSIE 9.0";
}else if (m8>-1){
brwsr ="MSIE 8.0";
}
return brwsr;
}
Try to use jquery, it will work in each browser
function validate() {
console.log("validation start");
var msg;
if($("input[name='userPass']").val().length >5)
console.log("good");//msg="good";
else
console.log("poor");// msg="poor";
document.getElementById("mylocation").innerText=msg;
}