我的脚本javascript如下:
email: {
required: true,
email: true
},
当在文本字段电子邮件中,我写道:chelsea@gmail
没有.com
,它是有效的。
有解决我问题的办法吗?
谢谢
编辑答案:
要验证电子邮件地址是否为name@domain.tld
格式,可以使用以下正则表达式:
var emailExp = new RegExp(/^b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b$/i);
此正则表达式只接受包含@符号、句点和2-4个字符长的TLD的电子邮件地址。
您可以使用上面的正则表达式来验证给定的电子邮件地址,如下所示:
function validate_email (email) {
/* Define the recommended regular expression. */
var emailExp = new RegExp(/^b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b$/i);
/* Test the email given against the expression and return the result. */
return emailExp.test(email);
}
jQuery验证器:
jQueryValidator不支持使用正则表达式,而是在内部使用默认的HTML5电子邮件正则表达式,因此您必须首先为验证器创建一个新的方法:
$.validator.addMethod(
/* The value you can use inside the email object in the validator. */
"regex",
/* The function that tests a given string against a given regEx. */
function(value, element, regexp) {
/* Check if the value is truthy (avoid null.constructor) & if it's not a RegEx. (Edited: regex --> regexp)*/
if (regexp && regexp.constructor != RegExp) {
/* Create a new regular expression using the regex argument. */
regexp = new RegExp(regexp);
}
/* Check whether the argument is global and, if so set its last index to 0. */
else if (regexp.global) regexp.lastIndex = 0;
/* Return whether the element is optional or the result of the validation. */
return this.optional(element) || regexp.test(value);
}
);
现在已经为验证器创建了一个支持针对正则表达式进行验证的方法,您可以按如下方式使用jQuery.validate
:
$('#element_id').validate({
email: {
required: true,
email: true,
regex: /^b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b$/i
}
});
原始答案(改进):
要过滤电子邮件地址并只接受类似name@domain.tld
的格式,请使用以下正则表达式:
var emailExp = new RegExp(/b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b/i);
此正则表达式过滤掉可能输入的任何"垃圾邮件",并要求存在一个@符号、一个点和一个2-4个字符长的TLD。如果给定电子邮件地址的子字符串与其匹配,则返回子字符串,否则返回false
。
您可以使用上面的正则表达式来过滤给定的电子邮件地址,如下所示:
function filter_email (email) {
var
/* Define the recommended regular expression. */
emailExp = new RegExp(/b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b/i),
/* Use 'match' to filter the email address given and cache the result. */
filtered = email.match(emailExp);
/* Return the filtered value or false. */
return filtered ? filtered[0] : false;
}
注意:
在一年多前回答OP的问题时,我误以为他对电子邮件验证的意图是试图过滤给定的字符串,只保留其中的一个子字符串,即电子邮件地址
此答案认为缺少TLD的地址无效,即使根据OP的请求,这些地址在现实世界中完全有效
尝试这个
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(function() {
// Setup form validation on the #register-form element
$("#login-form").validate({
// Specify the validation rules
rules: {
email: {
required: true,
email: true
}
},
// Specify the validation error messages
messages: {
email: "Please enter a valid email address"
},
submitHandler: function(form) {
form.submit();
}
}); });
我希望这对有帮助
https://jsfiddle.net/dave17/bex78vvs/
var re=new RegExp();
re = /^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})$/i;
if(re.test(Email_Value)){
alert("valid email");
}