-1

I'm trying to add a CSS class to a textbox when validation fails.

@Html.TextBoxFor(x => x.AdminUser.Username, new
{
    @id = "Username",
    @name = "Username",
    @type = "text",
    @class = "form-control",
    @placeholder = "Kullanıcı Adı",
    @autocomplete = "off"
})
@Html.ValidationMessageFor(x => x.AdminUser.Username, null, new { @class = "text-danger text-12 pl-10" })

Is it possible to add a callback to it? Or anyway else?

Solution for me:

Overriding onError class of unobtrusive validation source js did the trick. Now I can able to access upper div element.

    if (replace) {
        container.empty();
        error.removeClass("input-validation-error").appendTo(container);
        error.closest("div").addClass("has-error");
    }
Alparslan
  • 54
  • 6

1 Answers1

1

The input will be added with input-validation-error class when the validation fails. So you can override that class like this with your custom styles:

.input-validation-error {
    // your styles
}

If you add the above style to your page it will affect all inputs. So, if you want to target specific elements, you can add a custom-error-message class

.custom-error-message.input-validation-error{
    // error styles
}

And then in the TextBox you want to target:

@Html.TextBoxFor(x => x.AdminUser.Username, new { @class = "custom-error-message form-control"})

Now your custom error styles will be added only to those with inputs with custom-error-message class.

adiga
  • 34,372
  • 9
  • 61
  • 83