问题描述
我有一个正则表达式,用于检查是否没有输入有效的电子邮件地址
I have a regex that check if no email address is input that works
$.validator.addMethod('contains_no_email', function (value, element) {
return this.optional(element) || /^(?!\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)/.test(value);
}, "Do not include an email address");
现在,我需要对其进行修改以检查字符串是否不包含电子邮件地址.
Now I need to modify it to check if a sting contains no email address.
我想要:
[email protected] 一些单词(正确)
一些单词 [email protected] (是)
一些单词 [email protected] 一些单词(正确)
some words [email protected] some words (True)
一些词(假)
推荐答案
您需要确保输入文本与包含电子邮件的字符串不匹配.因此,您可以在此处遵循两种方法:
You need to make sure the input text does not match a string that contains an email. So, you can follow two approaches here:
-
使用
/\ w +(?:[-+.'] \ w +)* @ \ w +(?:[-.] \ w +)* \.\ w +(?:[-.] \ w +)*/
正则表达式并设置contains_no_email:false
使用正则表达式匹配任何字符串,但匹配包含类似于电子邮件的字符串且带有 /^(?![^] *?\ w +(?:[-+.'] \ w +)* @ \ w +(?:[-.] \ w +)* \.\ w +(?:[-.] \ w +)*)/ 并使用 contains_no_email:true
.
Use a regex that matches any string but a string containing an email-like string with /^(?![^]*?\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*)/
and use contains_no_email: true
.
您可以通过更改 contains_no_email
值来交换逻辑.
You may swap the logic by changing the contains_no_email
value.
以下是示例解决方案:
$.validator.addMethod('contains_no_email', function (value, element) {
return this.optional(element) ||
/^(?![\s\S]*?\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*)/.test(value);
}, "Do not include an email address"
);
$('#myform').validate({
// other options,
rules: {
"email": {
required: true,
contains_no_email: true
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/additional-methods.js"></script>
<form id="myform">
<input type="text" name="email" /><br/>
<br/>
<input type="submit" />
</form>
这篇关于修改正则表达式以检查字符串是否在jquery中不包含电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!