用于电子邮件和空字符串的Javascript正则表达式

时间:2015-10-14 06:49:17

标签: javascript regex

我使用此正则表达式/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/验证电子邮件格式,但当我将电子邮件字段留空时,会显示格式无效的错误。有人可以帮我解决如何为空字符串添加正则表达式吗?

3 个答案:

答案 0 :(得分:0)

^(?:[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6})?$

您可以将所有内容放入group并使该组可选。请参阅演示。

https://regex101.com/r/mG8kZ9/12

答案 1 :(得分:0)

我几天前就一样需要,所以我为它创建了一个单独的功能,因此它可以被多个电子邮件字段和其他文本字段使用。

虽然提供的正则表达式适用于所有有效的电子邮件,但您可以根据自己的需要进行限制。

 function IsValidEmailAddress(selectorElement) {

var emailAddress = $(selectorElement).val();
emailAddress = emailAddress.trim();

//All valid email pattern,a-z,0-9 etc [from stack overflow]
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

//Test the pattern with input emailAddress
if (pattern.test(emailAddress)) {

   //Put your own logic here

    if ($(selectorElement).parent().hasClass('error')) { 
        $(selectorElement).parent().removeClass('error');
    }
    return true;
}

if (!IsNullOrEmptyElement(selectorElement)) {

  //put your own logic here

    $(selectorElement).parent().addClass('error');
    $(selectorElement).val('');
    $(selectorElement).attr("placeholder", "Add Valid Email Address.");
}
return false;
};


//Function checks wether the element is Null or empty
function IsNullOrEmptyElement(selectorElement) {
var textboxText = $(selectorElement).val();

textboxText = textboxText.trim();

if (textboxText == null || textboxText == "") {
    $(selectorElement).parent().addClass('error');
    $(selectorElement).attr("placeholder", "This field is required.");
    return true;
}
$(selectorElement).parent().removeClass('error');
return false;

}

答案 2 :(得分:0)

您可以使用private static boolean isYearBetween(String start, String end) { DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate startDate = LocalDate.parse(start, pattern); LocalDate endDate = LocalDate.parse(end, pattern); Period between = Period.between(startDate, endDate).normalized(); return Period.ofYears(1).equals(between.isNegative() ? between.negated() : between); } 运算符与|匹配空字符串。

^$