简体   繁体   中英

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. In the model for one of the fields I have a RegularExpression attribute defined as follows:

[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

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.

Is it possible to turn off client side validation for the RegularExpression attribute without turning it off for the Required attribute?

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. You only have to implement constructor. Without IClientValidatable, the client side validators won't be wired up. Since this attribute is nothing but regular expression attribute, all server side validations will continue to work as provided by 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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