Javascript表单验证提交错误 [英] Javascript form validation submit errors

查看:139
本文介绍了Javascript表单验证提交错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我在网络上看到的所有内容看来,下面的代码应该做以下事情(这是我的期望):


  • 如果电子邮件(aid)与正则表达式不匹配,则显示警告消息并返回false

  • 如果密码(pass)为空,则显示警告消息并返回false

  • 如果两个条件都通过验证,请提交表单



Javascript如下所示: / p>

  function validate(){
var email = document.getElementById('aid')。value;
var pass = document.getElementById('apw')。value;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-ZA-Z]{2,4} $ /;
if(!emailPattern.test(email)){
alert(不是有效的电子邮件地址);
返回false;
}
if(pass == null || pass ==){
alert(Password is blank);
返回false;
}
返回true;
}

标签的开头如下:

 < form action =choose.phponsubmit =validate();方法= POST > 

我遇到的问题是,当点击提交按钮时,会弹出警告消息,但是然后choose.php加载到浏览器中。如果错误条件被触发,我希望脚本保留在页面上,直到两个条件都通过。 你需要将您的onSubmit更改为 onSubmit =return validate();。这样当它返回false时,表单不会被提交。现在它只是调用validate()函数并继续提交表单


From everything I've seen around the net, it appears that the following code should do the following (and this is my expectation):

  • If the email ("aid") does not match the regex, show alert message and return false
  • If the password ("pass") is blank, show alert message and return false
  • If both conditions pass validation submit the form

The Javascript is as follows:

function validate() {
var email = document.getElementById('aid').value;
var pass = document.getElementById('apw').value;        
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
if (!emailPattern.test(email)) {
    alert("Not a valid email address");
    return false;
}
if (pass == null || pass == "") {
    alert("Password is blank");
    return false;   
}
return true;
}

The opening for tag is as follows:

<form action="choose.php" onsubmit="validate();" method="post">

The problem I'm having is that when the submit button is clicked, the alert message will pop up, but then choose.php is loaded in the browser. I want the script, if the error conditions are triggered, to remain on the page until both conditions are passed.

解决方案

You need to change your onSubmit to onSubmit="return validate();". This way when it returns false, the form doesn't get submitted. Right now it just calls the validate() function and continues on with submitting the form

这篇关于Javascript表单验证提交错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆