我有两个用于订阅的单选按钮。如果客户选择是单选按钮,那么我将显示输入电子邮件地址文本框。如果客户选择是,则电子邮件地址文本框为必填项。如何在模型内部添加条件验证?
型号:
public class CustomerModel
{
[Required]
public bool Subscribe {get; set;}
[RequiredIfYes]
public string Email {ger; set;}
}
自定义验证类:
public class RequiredIfYesAttribute : Attribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == "Yes")
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Email is Required.");
}
}
}
查看:
<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)
@Html.ValidationMessageFor(model => model.Email)
</div>
</div>
答案 0 :(得分:0)
请尝试使用以下代码进行自定义验证:
public class RequiredIfYesAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var radioName = validationContext.ObjectInstance.GetType().GetProperty("Subscribe");
string radioValue = radioName.GetValue(validationContext.ObjectInstance, null)?.ToString();
var emailName = validationContext.ObjectInstance.GetType().GetProperty("Email");
string emailValue = emailName.GetValue(validationContext.ObjectInstance, null)?.ToString();
if (radioValue == "Yes" && string.IsNullOrEmpty(emailValue))
{
return new ValidationResult("Email is Required.");
}
else
{
return ValidationResult.Success;
}
}
}