SwordW
SwordW

Reputation: 610

How to validate textbox while user are typing values Using javascript

I have some troubles to validate user input while they are typing.

For example: the valid range is 600-800 and user is trying to type 700

When textbox is empty: show nothing

When textbox is 7: show red

When textbox is 70: show red

When textbox is 700:show nothing

I hope I can do it in js, can anyone help me?

Upvotes: 6

Views: 19501

Answers (5)

Protector one
Protector one

Reputation: 7261

You could use both the input and change events. Input will fire when a key press results in a character input. Change will fire when the focus of the text field is lost after the value of the field has changed, and I think in most browsers also after text is pasted into it from the clipboard.

document.getElementById('validate').addEventListener('input', pressHandler);
document.getElementById('validate').addEventListener('change', pressHandler);

Upvotes: 0

Canolyb1
Canolyb1

Reputation: 724

Here is another example, looks like your question was already answered as I was writing this.

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset = "utf-8">
    <style>
        .red {
            background-color: red;
        }
    </style>
    </head>
    <body>
        <form id="myForm">
        <input type="text" id="validate" class=""/>
        </form>
    <script>
    function pressHandler(e) {
        console.log(this.value);
        if (parseInt(this.value) <= 700) {
            this.className = "red";
        } else {
            this.className = "";
        }
    }

    document.getElementById("validate").addEventListener("keyup",pressHandler);
    </script>

    </body>
</html>

Upvotes: 1

Alexandre Nicolas
Alexandre Nicolas

Reputation: 1949

Here is an example:

<input type="text" id="myTextBox" onKeyUp="checkInput()" />
<script>
var myTextBox = document.getElementById('myTextBox');
function checkInput() {
  var value = myTextBox.value;
  if (!value || isNaN(value) || parseInt(value, 10) < 700 || parseInt(value, 10) > 800) {
    myTextBox.style.backgroundColor = 'red';
  } else {
    myTextBox.style.backgroundColor = 'green';
  }
}
</script>

Upvotes: 5

Ryan Holmes
Ryan Holmes

Reputation: 557

The on keyUp event can be used for this, have a look here

Keyp up event

Upvotes: 2

ded
ded

Reputation: 150

Sounds like you are using the onchange event.

If you try onkeypress it should do what you are after.

Upvotes: 0

Related Questions