Asp.Net MVC - Change error class name
Asked Answered
S

3

16

When I do field validation in Asp.Net MVC, it's generated the following error css classes :

  • input-validation-error
  • field-validation-error

Is there a way that I can change the names of the error classes that are generated?

I use xVal.

Synesthesia answered 11/1, 2010 at 19:52 Comment(0)
P
12

I don't know about xVal but as far as the ASP.NET MVC side of things go, if you have a look at the source you'll see there are some static readonly strings that represent these values.

public static readonly string ValidationInputCssClassName = "input-validation-error";
public static readonly string ValidationMessageCssClassName = "field-validation-error";
public static readonly string ValidationSummaryCssClassName = "validation-summary-errors";

So either you edit the source to your liking (which may also fix xVal) or alter the outputting code to use different values somehow.

If xVal is using jQuery Validation (which I think it does...?) you could change it's default value for the 'errorClass' option. My answer here could help you along that path.

HTHs,
Charles

Presidentelect answered 11/1, 2010 at 20:21 Comment(0)
C
3

Here's what I did:

private void ChangeValidationClassNames()
{
    var helper = new HtmlHelper(new ViewContext(), new ViewPage());
    SetPublicStaticReadonly("ValidationInputCssClassName", helper, "errInput");
    SetPublicStaticReadonly("ValidationMessageCssClassName", helper, "errMsg");
}

public void SetPublicStaticReadonly(string readonlyPropName, object instance, object value)
{            
    var field = instance.GetType().GetField(readonlyPropName, BindingFlags.Static | BindingFlags.Public);
    if (field == null)
        throw new NullReferenceException(string.Format("public static readonly field '{0}' not found in '{1}'", readonlyPropName, instance));
    field.SetValue(instance, value);
}
Covington answered 17/5, 2011 at 5:16 Comment(1)
@TweetZz: you don't need an HtmlHelper instance to change static fields. you can get the field just from typeof(HtmlHelper), and call SetValue(null, value).Spectroscopy
P
0

More cleaner solution may be:

<script type="text/javascript">
    $(document).ready(function(){
        $('.input-validation-error').addClass('CustomErrorClass').removeClass('input-validation-error');
        $('.field-validation-error').addClass('CustomErrorClass').removeClass('field-validation-error');
    });
</script>
Probst answered 6/1, 2016 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.