我有一个联系表格,其中需要姓名、联系方式(电子邮件或电话)、电子邮件或电话文本字段(取决于单击的单选按钮)和描述。我正在使用 jQuery 的验证插件进行验证。单击电子邮件单选按钮时会出现电子邮件字段,电话字段也是如此。我的问题是代码如何在单击电子邮件单选按钮时验证电子邮件文本字段,并在单击电话单选按钮时验证电话文本字段。其中之一应该是必需的,但不是两者都需要。如果有帮助,当我单击电子邮件单选按钮时,电子邮件文本字段出现,电话文本字段消失,反之亦然。
HTML
<div class="control-group">
<label class="control-label" for="contact_name">Name</label>
<div class="controls">
<input id="contact_name" name="contact[name]" size="30" type="text" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="How_would_you_like_to_be_contacted_">How would you like to be contacted?</label>
<div class="controls">
<label class="radio">
<input id="contact_type_email" name="contact_type" type="radio" value="email" />
<label for="Email">Email</label>
</label>
<label class="radio">
<input id="contact_type_telephone" name="contact_type" type="radio" value="telephone" />
<label for="Telephone">Telephone</label>
</label>
</div>
</div>
<div class="control-group" id="email">
<label class="control-label" for="contact_email">Email</label>
<div class="controls">
<input id="contact_email" name="contact[email]" size="30" type="text" />
</div>
</div>
<div class="control-group" id="telephone">
<label class="control-label" for="contact_telephone">Telephone</label>
<div class="controls">
<input id="contact_telephone" name="contact[telephone]" placeholder="###-###-####" size="30" type="text" />
</div>
</div>
jQuery
$(document).ready(function() {
$('#email').hide();
$('#telephone').hide();
var email = false;
var telephone = false;
$('#contact_type_email').click(function() {
$('#email').show();
$('#telephone').hide();
email = true;
telephone = false;
});
$('#contact_type_telephone').click(function() {
$('#telephone').show();
$('#email').hide();
telephone = true;
email = false;
});
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) ||
phone_number.match(/^[2-9]\d{2}-[2-9]\d{2}-\d{4}$/);
}, "Please specify a valid phone number");
$('#new_contact').validate({
ignore: ":hidden",
rules: {
'contact[name]': {
required: true
},
'contact[email]': {
required: true,
email: true
},
'contact[telephone]': {
required: true,
phoneUS: true
},
'contact[description]': {
required: true
},
contact_type: {
required: true
}
},
messages: {
'contact[name]': {
required: "Please provide a name."
},
'contact[telephone]': {
required: "Please provide a valid telephone number."
},
'contact[description]': {
required: "Please provide a description of the work you would like done."
}
},
errorPlacement: function(error, element) {
error.appendTo("#error");
}
});
});
我尝试用 vars 做一些事情,email
但telephone
不确定是否需要它们。