基于 RadioButton 选择的多重验证?
Multiple validations based on RadioButton selection?
我目前正在尝试验证我的 MVC 视图中的文本字段是否满足多个条件。
- 总的来说,该字段不能为空。
- 将有一个具有选项
A
或 B
的单选按钮组。如果选择 A
,我将需要确保输入的内容是我正在与之比较的数据集中的有效条目。如果选择B
,那么我就不需要执行这个验证了。
我已经进行了验证以防止文本字段为空,并验证输入的内容与数据集中的内容。我正在尝试添加 RadioButtons。
目前我正在使用 DataAnnotations
验证我的表单。目前我总是使用远程验证器来验证文本字段。这是我在视图模型中的条目。
[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")]
public string Account { get; set; }
我不确定如何根据在 RadioButton 中选择的内容添加另一级别的验证。
您可以使用 [Remote]
属性的 AdditionalFields
属性 将所选单选按钮的值传递给控制器。假设属性你绑定的单选按钮的名称是Option
,那么
[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", AdditionalFields = "Option", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")]
public string Account { get; set; }
并修改控制器方法以接受 Account
和 Option
的值
public ActionResult ControllerMethod(string account, string option)
{
if (option == "B")
{
return true; // ignore it and indicate success
}
else
{
// call service to validate and return result
}
}
我目前正在尝试验证我的 MVC 视图中的文本字段是否满足多个条件。
- 总的来说,该字段不能为空。
- 将有一个具有选项
A
或B
的单选按钮组。如果选择A
,我将需要确保输入的内容是我正在与之比较的数据集中的有效条目。如果选择B
,那么我就不需要执行这个验证了。
我已经进行了验证以防止文本字段为空,并验证输入的内容与数据集中的内容。我正在尝试添加 RadioButtons。
目前我正在使用 DataAnnotations
验证我的表单。目前我总是使用远程验证器来验证文本字段。这是我在视图模型中的条目。
[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")]
public string Account { get; set; }
我不确定如何根据在 RadioButton 中选择的内容添加另一级别的验证。
您可以使用 [Remote]
属性的 AdditionalFields
属性 将所选单选按钮的值传递给控制器。假设属性你绑定的单选按钮的名称是Option
,那么
[Required(ErrorMessage = "{0} is required")]
[Remote ("ControllerMethod", "Controller", AdditionalFields = "Option", ErrorMessage = "{0} is not a in the data set.")]
[Display(Name = "Account")]
public string Account { get; set; }
并修改控制器方法以接受 Account
和 Option
public ActionResult ControllerMethod(string account, string option)
{
if (option == "B")
{
return true; // ignore it and indicate success
}
else
{
// call service to validate and return result
}
}