简体   繁体   中英

Form validation using AJAX

I'm making a log-in form with 3 input fields(text for username, password for password and submit for logging in).

看起来像这样:

As you can see, I am using AJAX to validate the log in directly at the client side.

var username = document.getElementById("username").getElementsByTagName("input")[0];
username.onfocus = function(){
    this.className = "thinking";
}
username.onblur = validateUsername;

and similarly for the password as well. The submit button is disabled by default and only enabled after both the fields are validated.

Here is my problem: After typing in the username and hitting the [Tab] button, my PHP script validates the username and shows the green tick as shown in the image. But when I type in the password, the user will have to manually click elsewhere to trigger the 'onblur' event and perform password validation which isn't very intuitive and appealing. The password checking should be done while the focus is still on the password field which means that when the user starts typing the password, one event should be fired and when he finishes typing, another event should be fired. How should I go about this?

Thank you!

You are using onBlur event which means that it will be triggered only when the field will be left unfocussed which is happening when you are pressing [Tab] key. In order to trigger the onBlur event on the password field you have to press [Tab] key again. You can also use HTML5 input tags which has default validations. If you want to fire an event when the user types then you can use keyup and keydown events. If you want to specifically fire one event when the user starts typing and one when he finishes then you have to assume some time he takes for typing. Take a look at this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM