在 Jquery Validation 中最多允许 10 封电子邮件,每个逗号分隔
Posted
技术标签:
【中文标题】在 Jquery Validation 中最多允许 10 封电子邮件,每个逗号分隔【英文标题】:Allow maximum of 10 Emails in Jquery Validation with each comma separated 【发布时间】:2015-10-07 22:39:33 【问题描述】:如何只允许和验证 10 封电子邮件或最少 10 封电子邮件,每个逗号分隔。它应该只允许 10 封电子邮件或最少,每封电子邮件都用逗号分隔。现在我只能验证用逗号分隔的每封电子邮件
<form method="post" action="" id="add_engagement" name="add_engagement" class="form-horizontal">
<tr><td>Email Recipients</td>
<td><textarea name="email_recipients" id="email_recipients" >$Notification.email_recipients</textarea><br/><span style="color:red">*</span>Note: Separated by commas(,)</td>
</tr>
<input type="submit" class="post_button" id="edit_notification" value="Update" name="edit_notification" /></td></tr>
</form>
<script>
$(function()
$('#edit_notification').one('click', function ()
jQuery.validator.setDefaults(
debug: true,
success: "valid"
);
$.validator.addMethod('multiEmails', function(value, element)
if (this.optional(element))
return true;
else
var valid = true;
$.each($.trim(value).replace(/,$/, '').split(','), $.proxy(function (index, email)
if (!$.validator.methods.email.call(this, $.trim(email), element))
valid = false;
, this));
return valid;
, 'One or more email addresses are invalid');
$("#add_engagement").validate(
rules:
email_recipients:
required: true,
multiEmails:true,
,
,
messages:
email_recipients:
required: "Please enter email",
,
,
submitHandler: function(form)
form.submit();
,
);<script>
【问题讨论】:
【参考方案1】:您可以添加计数器:
var ec = 0;
$.each($.trim(value).replace(/,$/, '').split(','), $.proxy(function (index, email)
ec++;
if (!$.validator.methods.email.call(this, $.trim(email), element))
valid = false;
, this));
if (ec<1 || ec>10) valid = false;
或者您可以在电子邮件地址数量上添加另一个验证规则,并带有单独的错误消息。
【讨论】:
以上是关于在 Jquery Validation 中最多允许 10 封电子邮件,每个逗号分隔的主要内容,如果未能解决你的问题,请参考以下文章