简体   繁体   English

是否可以在MVC中禁用单个模型属性的客户端验证

[英]Is it possible to disable client side validation for a single model property in MVC

I have an MVC 4 model and am creating html from it in the view using @Html.TextBoxFor. 我有一个MVC 4模型,并使用@ Html.TextBoxFor在视图中创建html。 In the model for one of the fields I have a RegularExpression attribute defined as follows: 在其中一个字段的模型中,我有一个RegularExpression属性,定义如下:

[Required(ErrorMessageResourceType=typeof(ResourceFile), ErrorMessageResourceName="ResourceName1"
[RegularExpression(@"\w{3,5}", ErrorMessageResourceType=typeof(ResourceFile), ErrorMessageResourceName="ResourceName2")]
public string TestProperty { get; set; }

Note the expression is more complex than this but what I have here is suitable for testing. 请注意表达式比这更复杂,但我在这里适合测试。 I have set up unobtrusive client side validation as described here: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html 我已经设置了不引人注意的客户端验证,如下所述: http//bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

The problem I have is that I need to accept Russian characters. 我遇到的问题是我需要接受俄语字符。 .Net's regular expressions have a different meaning for \\w to javascript's regular expressions and as such server side validation works as I expect and client side does not. .Net的正则表达式对于\\ j到javascript的正则表达式具有不同的含义,因此服务器端验证的工作方式与我预期的相同,而客户端则不然。

Is it possible to turn off client side validation for the RegularExpression attribute without turning it off for the Required attribute? 是否可以关闭RegularExpression属性的客户端验证而不关闭Required属性?

Failing that is it possible to just turn off client side validation for this single property without switching off for all the other properties on that model object? 如果不这样做就可以关闭这个单一属性的客户端验证而不关闭该模型对象上的所有其他属性?

Create your own server side only regular expression attribute. 仅创建自己的服务器端正则表达式属性。 Derive it from RegularExpressionAttribute but don't implement IClientValidatable. 从RegularExpressionAttribute派生它,但不实现IClientValidatable。 You only have to implement constructor. 您只需要实现构造函数。 Without IClientValidatable, the client side validators won't be wired up. 如果没有IClientValidatable,客户端验证器将不会被连线。 Since this attribute is nothing but regular expression attribute, all server side validations will continue to work as provided by RegularExpressionAttribute. 由于此属性只是正则表达式属性,因此所有服务器端验证将继续按RegularExpressionAttribute的提供工作。

public class ServerSideOnlyRegularExpressionAttribute : RegularExpressionAttribute
{
    public ServerSideOnlyRegularExpressionAttribute(string pattern)
        : base(pattern)
    {
    }
}

Use it as 用它作为

[Required(ErrorMessageResourceType=typeof(ResourceFile), ErrorMessageResourceName="ResourceName1"
[ServerSideOnlyRegularExpression(@"\w{3,5}", ErrorMessageResourceType=typeof(ResourceFile), ErrorMessageResourceName="ResourceName2")]
public string TestProperty { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM