简体   繁体   English

使用AJAX进行表单验证

[英]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). 我正在制作一个包含3个输入字段的登录表单(用户名文字,密码密码和提交登录)。

看起来像这样:

As you can see, I am using AJAX to validate the log in directly at the client side. 如您所见,我正在使用AJAX直接在客户端验证登录。

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. 这是我的问题:输入用户名并单击[Tab]按钮后,我的PHP脚本将验证用户名并显示绿色勾号,如图所示。 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. 但是,当我输入密码时,用户将不得不手动单击其他地方以触发“ onblur”事件并执行密码验证,这不是很直观且很吸引人。 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. 您正在使用onBlur事件,这意味着仅当您按下[Tab]键时,当该字段保持不聚焦状态时才会触发该事件。 In order to trigger the onBlur event on the password field you have to press [Tab] key again. 为了在密码字段上触发onBlur事件,您必须再次按[Tab]键。 You can also use HTML5 input tags which has default validations. 您还可以使用具有默认验证的HTML5输入标签 If you want to fire an event when the user types then you can use keyup and keydown events. 如果要在用户键入时触发事件,则可以使用keyup和keydown事件。 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 . 看一下这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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