需要验证只有在现场可见 [英] Require validation only if the field is visible

查看:174
本文介绍了需要验证只有在现场可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的ASP.NET MVC 3。

客户端验证 [必需] 属性

类看起来:

 公共类用户
{
    [必需(的ErrorMessage =名要求)]
    公共字符串名字{获得;组; }
}

我要的字段,只有当它是可见的,这将显示只在某些特定条件下进行验证。我该怎么做?

我用以下,但它仍然看起来,以验证该隐藏字段的必填字段。

  $('#registerForm')验证({忽略:不(:可见)});


解决方案

从@Josiah一些有用的提示,我能够得到我的要求。

添加RequiredIfAttribute类和所需的JavaScript。请参阅<一个href=\"http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx\">Conditional验证在ASP.NET MVC 3

和在类中添加 RequiredIf 属性为:

 公共类用户
{
[RequiredIf(hFirstName,真,的ErrorMessage =第一名称是必需)]
公共字符串名字{获得;组; }

在ASPX:

  @ Html.TextBoxFor(型号=&GT; Model.FirstName,新{@style =高度:自动;})
@ Html.ValidationMessageFor(型号=&GT; Model.FirstName)
@ Html.Hidden(hFirstName)

设置 hFirstName 的价值为true,如果名字字段是隐藏的假,如果可见。

神品这些变化。感谢@Josiah Ruddell他的<一个href=\"http://stackoverflow.com/questions/5731788/required-validation-only-if-the-field-is-visible-in-asp-net-mvc/5731975#5731975\">answer

I am using the [Required] attribute for the client-side validation in ASP.NET MVC 3.

The class looks as:

public class User
{
    [Required(ErrorMessage = "First Name is required")]
    public string FirstName { get; set; }
}

I want the field FirstName to be validated only if it's visible, which will be shown only on certain conditions. How can I do that?

I have used the following, but still it looks to validate for the required field of that hidden field.

$('#registerForm').validate({ ignore: ":not(:visible)" });

解决方案

With some useful hints from @Josiah, i am able to get to my requirement.

Add the RequiredIfAttribute class and the required javascript. Refer Conditional Validation in ASP.NET MVC 3

And in the class add the RequiredIf attribute as:

public class User
{
[RequiredIf("hFirstName", "true", ErrorMessage = "First Name is required")]
public string FirstName { get; set; }

and in aspx:

@Html.TextBoxFor(model => Model.FirstName, new { @style = "height:auto;" })
@Html.ValidationMessageFor(model => Model.FirstName)
@Html.Hidden("hFirstName")

Set the value of hFirstName to 'true' if the FirstName field is hidden and 'false', if visible.

The magic works with these changes. Thanks to @Josiah Ruddell for his answer

这篇关于需要验证只有在现场可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆