简体   繁体   English

如何在我的javascript表单验证中添加正则表达式测试?

[英]How do i add a regex test to my javascript form validation?

I have created a simple form validation using javascript and want to add some pattern tests to the inputs to make sure the correct information is submitted obviously but im very new to this and am looking to see if someone can help me out with regards to adding the pattern tests. 我已经使用javascript创建了一个简单的表单验证,并希望在输入中添加一些模式测试,以确保显然提交了正确的信息,但我是非常新的,我正在寻找是否有人可以帮助我关于添加模式测试。

my validation code so far is: 到目前为止我的验证码是:

function validate(form) {
var fail = false;
var name = document.getElementById("full_name");

if (name.value.length == 0) {
  document.getElementById("okName").className = "fail";
  fail = true;
}else{
  document.getElementById("okName").className = "success";
}



var email = document.getElementById("email");
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

if (email.value.length == 0) {
  document.getElementById("okEmail").className = "fail";
    fail = true;
}else{
  document.getElementById("okEmail").className = "success";
}

} }

I think that I have to add the condition to the "if" statement for the email validation but havn't a clue where to begin? 我认为我必须将条件添加到电子邮件验证的“if”语句中,但是不知道从哪里开始? I know how i would do it using jQuery: 我知道如何使用jQuery做到这一点:

if( value.length<1 /*|| value==field_values[$(this).attr('id')]*/ || ( $(this).attr('id')=='email' && !emailPattern.test(value) )  )

but im not sure how to do the same in raw javaScript as I dont know how to target the input for the email in plain javascript! 但我不知道如何在原始javaScript中做同样的事情,因为我不知道如何在普通的javascript中定位电子邮件的输入! If anyone can help me out it would really be appreciated! 如果有人可以帮助我,真的很感激!

This would look like: 这看起来像:

var email = document.getElementById("email");
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

if (!emailPattern.test(email.value)) {
  document.getElementById("okEmail").className = "fail";
    fail = true;
}else{
  document.getElementById("okEmail").className = "success";
}

There is no need to check for length of string as well. 也没有必要检查字符串的长度。 No need to jQuerize your webpage for such a simple taks. 无需为了这么简单的设置而对您的网页进行jQuerize。 :-) :-)

Some advice: 一些忠告:

  • never rely on client-side validation only 从不依赖客户端验证
  • verify if control actually exists (ie if (email) { ... } ) 验证控件是否确实存在(即if(email){...})
  • trim strings or provide patterns for name as well (your form validates with single space character entered into form field) 修剪字符串或为名称提供模式(您的表单在表单字段中输入单个空格字符进行验证)
  • also your e-mail pattern is not correct actually (dot is "any character" also in [ ]) 实际上你的电子邮件模式也不正确(点也是[]中的“任何字符”)
if (email.value.length === 0 || !emailPattern.test(email.value) ) {
  document.getElementById("okEmail").className = "fail";
  fail = true;
} else {
  document.getElementById("okEmail").className = "success";
}

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

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