[英]TLD validation for email address in javascript
我正在验证一个电子邮件地址。 但这并不能验证我是否使用了正确的tld。 我只想验证.com,.in,.org,.gov和.jo。该怎么做? 我的代码是这样的:
function validateConsumerEmail(){
email = document.getElementById('customer_email').value;
if ((email == null)||(email == "")){
alert("Please Enter a Valid Consumer Email Address...")
document.consumerEmail.customer_email.focus();
return false
}
if (echeck(email)==false){
email=""
document.consumerEmail.customer_email.focus();
return false
}
if(email != ''){
var splitting = email.split('@');
if(!isNaN(splitting[0])){
alert('Please provide proper email address...');
document.consumerEmail.customer_email.focus();
return false;
}
if(splitting[0].length<6 || splitting[0].length > 250){
alert('Please provide proper email address...');
document.consumerEmail.customer_email.focus();
return false;
}
}
}
其中customer_email是字段名称的ID。
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Please provide valid email ID.");
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Please provide valid email ID.");
return false
}
if (str.indexOf(" ")!=-1){
alert("Please provide valid email ID.");
return false
}
return true
}
尝试这个。 为了验证电子邮件地址,您确实要使用REGEX,因为您的当前代码允许通过各种无效的电子邮件,并且不允许许多有效的电子邮件。
就是说,能够真正验证任何有效的电子邮件是一个讨论点,并且已经存在了多年。 我的示例基于此电子邮件匹配器REGEX的改编版本。
我还简化了您的代码。 由于您未提供此信息,因此我忽略了echeck
的电话。 根据需要将其重新添加。
function validateConsumerEmail(){
//prep
var email = document.getElementById('customer_email'), error;
//validate
if (!email.value || !/^[\w\.%\+\-]+@[a-z0-9.-]+\.(com|gov|in|jo|org)$/i.test(email.value))
error = 'Please enter a valid e-mail, with the domain .com, .in, .org, .jo or .gov';
//feedback
if (error) {
email.focus();
return false;
} else {
//OK - do something here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.