2

how to validate the input while entering the data using Jquery event?

 $("#lname").blur(function() {
        if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
            $("#lname").css({"border":"1px solid #cecece"});
            $("#error_lname").css("display","none");
        }
        else{
            $("#error_lname").css("display","block");
        }
    });

2 Answers 2

1

If you want to validate as the user types, use the input event instead of blur:

$("#lname").on('input', function() {
    if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
        $("#lname").css({"border":"1px solid #cecece"});
        $("#error_lname").css("display","none");
    }
    else{
        $("#error_lname").css("display","block");

    }
});

You should however note that to follow best practices you should avoid using css() and instead add/remove a class that's defined in an external stylesheet, something like this:

$("#lname").on('input', function() { 
    var $el = $(this);
    var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
    $el.toggleClass('invalid', !valid);
    $el.next('.error-msg').toggle(!valid);
});
.invalid { border: 1px solid #CECECE; }

Note that the above is assuming the input you're validating has a following sibling which is the error message which has the class of .error-msg. Organising the logic in this way means that the validation logic can easily be genericised - instead of being tied to each control due to the #error_lname selector.

Sign up to request clarification or add additional context in comments.

Comments

1

The answer of Rory is perfect I just want to add that you can also use onkeyup event also to get the same effect.

$("#lname").on('keyup', function() { 
    var $el = $(this);
    var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
    $el.toggleClass('invalid', !valid);
    $el.next('.error-msg').toggle(!valid);
});
.error-msg{
  display:none;
  color:red;
}

.invalid{
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="lname">Last Name:</label>
<input type="text" id="lname">
<span class="error-msg">Error message here ...</span>

2 Comments

Just be aware that this won't fire if pasted in via the mouse.
Yes that's true and I just realize it when I just tested it. Thanks I've learned also something new :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.