基于单选按钮选择,我有这2个单选按钮,我应该显示文本框,也应该验证文本框。如果我选择单选按钮是,文本框为null,则应该显示错误。使用下面的代码,我只能显示和隐藏文本框,而不能验证文本框。请提出解决方案。
型号:
public class CustomerModel
{
[Required(ErrorMessage = "Please select subscribe option")]
public bool Subscribe {get; set;}
public string Email {get; set;}
}
视图:
function ShowHideDiv() {
var chkYes = document.getElementById("Yes");
var dvtext = document.getElementById("dvtext");
dvtext.style.display = chkYes.checked ? "block" : "none";
}
$(function () {
warningel = document.getElementById('lbError');
$("#radio").submit(function () {
if ($('#Yes').is(':checked') && !$.trim($('#Email').val())) {
warningel.innerHTML = "Please Enter Email";
return false;
}
});
});
<div class="form-group col-md-12 ">
<label class="required" for="subscribe">Email Subsciption</label>
<span >Yes : <input type="radio" value="Yes" name="Subscribe" id="chkYes" onclick="ShowHideDiv()" /></span>
<span >No : <input type="radio" value="No" name="Subscribe" id="chkNo" onclick="ShowHideDiv()" /></span>
@Html.ValidationMessageFor(model => model.Subscribe)
</div>
<div id="dvtext" style="display: none">
<label for="email" class="required">Enter Email</label>
<div style="width:300px;">
@Html.TextBoxFor(model => model.Email)
<div id='lbError' style="color: red;"></div>
@Html.ValidationMessageFor(m => m.Email)
</div>
</div>
答案 0 :(得分:0)
我认为,更干净的解决方案是仅使用javascript来显示/隐藏文本框,并让MVC处理验证,您可以仅通过继承$('.variations select').each(function (i, select) {
var $select = jQuery(select);
$select.find('option').each(function (j, option) {
var $option = jQuery(option);
// Create a radio:
var $radio = jQuery('<input type="radio" />');
// Set name and value:
$radio.attr('name', $select.attr('name')).attr('value', $option.val());
// Set checked if the option was selected
if ($option.attr('selected')) $radio.attr('checked', 'checked');
// Insert radio after select box:
$select.after($radio);
$radio.wrap('<div class="variation-wrap" />');
// Insert a label:
$radio.after(
$("<label />").attr('for', $select.attr('name')).text($option.text())
);
});
});
来获得验证。
假设您在某处有一个IValidatableObject
自定义方法来检查提供的字符串:
isValidEmail()