简体   繁体   English

Javascript Regex表单验证返回错误

[英]Javascript Regex Form validation returning error

I have been trying to validate my form email input with these line of codes. 我一直在尝试使用这些代码行来验证表单电子邮件输入。

 function validate() { var emailFirst = document.getElementById('email1'); var emailFirstRGex = /^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; var emailFirstTest = emailFirstRGex.test(emailFirst); if (emailFirstTest === false) { alert('hello20'); } } 

My form 我的表格

 <form class="needs-validation" novalidate method="POST" action="nomination2.php" onsubmit="validate()"> 

I keep getting the hello20 response. 我一直收到hello20的回应。 Meanwhile i have tried this regex against emails on the console without error. 同时,我已经在控制台上针对电子邮件尝试了此正则表达式,而没有出现错误。 How do I solve this? 我该如何解决?

emailFirstTest is declared inside your function, so checking for it outside the function means it is out of scope and doesn't exist. emailFirstTest在函数内部声明,因此在函数外部进行检查意味着它超出范围且不存在。

Just define it above your function: 只需在函数上方定义它:

var emailFirstTest  = '';

function validate() {
  emailFirst = document.getElementById('email1');
  var emailFirstRGex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  var emailFirstTest = emailFirstRGex.test(emailFirst);
}

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

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