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 Overflow
Top answer
1 of 3
1

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 ");
    }

}  
2 of 3
0
$('#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,

  1. Check if value is empty (If empty don't perform anything)
  2. If not empty check if the value matches to defined set
  3. 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.
  4. 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.
  5. 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.

🌐
W3Schools
w3schools.com β€Ί jsref β€Ί event_onkeyup.asp
onkeyup Event
<element onkeyup="myScript"> Try it Yourself Β» Β· In JavaScript: object.onkeyup = function(){myScript}; Try it Yourself Β» Β· In JavaScript, using the addEventListener() method: object.addEventListener("keyup", myScript); Try it Yourself Β» Β· Using "onkeydown" together with the "onkeyup" event: <input type="text" onkeydown="keydownFunction()" onkeyup="keyupFunction()"> Try it Yourself Β» Β·
Discussions

validating on keyup
Hello everybody; I'm trying to validate the text of an input as it is typed. I have this keyup: $(".ent").keyup(function(){ $(this).val( $(this).val().replace(/[^0-9\.]/g, "") ); }); The idea is that only let the user type a decimal number; and it does. The only problem is that it let type ... More on forum.jquery.com
🌐 forum.jquery.com
jQuery.validate.js onkeyup = true error - Stack Overflow
With my jquery validation configuration, I get the following error when setting onkeyup to true. It works if I set it to false, but I don't get validation feedback until I blur the field, and I'm l... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Validation on onKeyUp - Stack Overflow
I need to do validation onkeyup and onsubmit. I have field called CVV which accepts 3 or 4 digits numbers, so i'm using '^(d){3,4}$'. This pattern works properly when i did in onsubmit function, bu... More on stackoverflow.com
🌐 stackoverflow.com
Field validation with JavaScript - onkeyup? - Stack Overflow
i have a code here triggered by an onkeypress... i want it to alert whenever there is a special character typed. Aside from an alert, if the user will type a special character in a field, the typed More on stackoverflow.com
🌐 stackoverflow.com
March 5, 2012
🌐
CodePen
codepen.io β€Ί adrianparr β€Ί pen β€Ί jaapxa
jQuery Validate onkeyup
Minimize JavaScript Editor Β· Fold All Β· Unfold All Β· var rowSelector = '.js-row'; $('#yourDetails').validate({ debug: true, onfocusout: function(element) { var $element = $(element); $element.valid(); }, onkeyup: function(element) { var $row = $(element).closest(rowSelector); if ($row.hasClass('is-row-error')) { $(element).valid(); } }, highlight: function (element, errorClass, validClass) { var $row = $(element).closest(rowSelector); $row.addClass('is-row-error'); $row.removeClass('is-row-valid'); }, unhighlight: function (element, errorClass, validClass) { var $row = $(element).closest(rowSelector); $row.addClass('is-row-valid'); $row.removeClass('is-row-error'); } }); !
🌐
C# Corner
c-sharpcorner.com β€Ί blogs β€Ί how-to-use-onkeyup-event-to-validate-in-javascript1
How to use onkeyup event to validate in JavaScript
May 18, 2012 - In your html page add the control you want to validate but for this sample I used textbox to demonstrate this code, in my textbox control i used onkeyup event to validate whether recently entered character is numeric or not. So you can call this JavaScript code as your requirement in your project.
🌐
Ricard Torres dev
ricard.dev β€Ί home β€Ί posts β€Ί validate input text on keyup with javascript
Validate input text on keyup with JavaScript - Ricard Torres dev
November 27, 2022 - // Run the code when the page is complete $(document).ready(function () { // Attach the event handler for the keyboard keyup $('.my-input').keyup(function () { var $th = $(this); // run the expression and replace with nothing $th.val($th.val().replace(/[^a-zA-Z0-9]/g, function () { return ''; })); }); });Code language: JavaScript (javascript)
🌐
Medium
seahyingqi.medium.com β€Ί registration-form-keyup-validation-f07c16e13409
Registration Form (keyup) live validation | by yingqi | Medium
December 28, 2021 - To ensure that the validation is shown live to users when they are keying in the details in the input box, instead of using β€˜click’, we use a β€˜keyup’ event where every key pressed and released is registered and used as a comparison to the regular expressions I have set.
🌐
JSFiddle
jsfiddle.net β€Ί bizamajig β€Ί qhj3fck3
JQUERY VALIDATE - ONKEYUP - OPTIONAL - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
Jquery
forum.jquery.com β€Ί portal β€Ί en β€Ί community β€Ί topic β€Ί validating-on-keyup
validating on keyup
Hello everybody; I'm trying to validate the text of an input as it is typed. I have this keyup: $(".ent").keyup(function(){ $(this).val( $(this).val().replace(/[^0-9\.]/g, "") ); }); The idea is that only let the user type a decimal number; and it does. The only problem is that it let type ...
Find elsewhere
Top answer
1 of 5
42

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()}
2 of 5
37

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);
    }
}
🌐
Innovasys
innovasys.com β€Ί samples β€Ί dx β€Ί dx.javascript.jquery β€Ί material β€Ί javascriptlibrary~jquery.validator.options~onkeyup.html
onkeyup Option
onkeyup Option Β· Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Syntax Β· Javascript (Usage) Javascript (Specification) var options; // Type: jQuery.validator.options var instance; // Type: ...
🌐
ASPSnippets
aspsnippets.com β€Ί Articles β€Ί Perform-Email-validation-using-OnKeyPress-in-JavaScript.aspx
Perform Email validation using OnKeyPress in JavaScript
January 28, 2019 - ValidateEmail JavaScript function. <input type="text" id="txtEmail" onkeyup="ValidateEmail();" />
🌐
Fromanegg
fromanegg.com β€Ί post β€Ί 2012 β€Ί 12 β€Ί 29 β€Ί form-validation-with-keydown-keypress-and-keyup
Form validation with keydown, keypress, and keyup Β· From An Egg
December 29, 2012 - var input = document.getElementsByName('currency-field')[0], currencyRegex = /^[0-9]{0,5}(\.[0-9]{0,2})?$/; function handleKeypress(e) { // Get the string value of the charCode. var char = String.fromCharCode(e.charCode), target = e.target, inputVal = target.value, // Construct what the value will be if the event is not prevented. value = inputVal.substr(0, target.selectionStart) + char + inputVal.substr(target.selectionEnd); // Test to make sure the user is inputting only valid characters // and that the resulting input is valid. if (!char.match(/[0-9.]/) || !value.match(currencyRegex)) { tog
Top answer
1 of 3
2

There are a few weird things going on here.

  1. You don't want to use the onkeyup attributes of HTML elements. Bind an event listener function, which keeps your code more modular.
  2. Like others said, you can't use the subtraction operator like that.
  3. 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/

2 of 3
1

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.

Top answer
1 of 3
2

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>
2 of 3
0

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();
    });
}
🌐
Html Hints
htmlhints.com β€Ί article β€Ί email-validation-in-javascript-using-regular-expression-with-match β€Ί 10
Email validation in javascript using regular expression with match() - Html Hints
In javascript you can easily validate email by using many javascript function such as onkeyup() onchange() and many more! After calling a function use RegExp of javascript to validate email
Top answer
1 of 3
4

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.

2 of 3
1

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