choose asp-validation-for css class

1.7k Views Asked by At

I was wondering if .NET core's asp-validation-for has a way to override the class that gets set on a span, or if there is a way to extend the tag helper to allow for that. Right now, when an error occurs client side, field-validation-error is the class that gets put on my span element. I was wondering if there is a way to override that within .NET Core or if I'll have to develop/modify that myself? This seems like a silly shortcoming, and I'd be surprised if there wasn't some other way of getting what I'm looking for.

The problem is I'm using bootstrap, and I want to add some bootstrap classes to my error element when a form doesn't pass validation.

1

There are 1 best solutions below

0
On

Have a look at the HTML it generates, which may differ on the version you have; with me, like with you for me it generates:

<span class="field-validation-error" data-valmsg-for="FirstName" data-valmsg-replace="false">First name is required</span>

So, the only thing I have to do is style the .field-validation-error class in ccs. as I normally do not have it as it's not generated in the File New Project template I just add it according to the specifications.

so in my site.css, I add

.field-validation-error
{
  color: red;
}

I usually also edit the input itself; assuming you also want to do that you could do something like this, adding a (!) error marker in the right side of the input:

.input-validation-error {
    border-color: #dc3545;
    padding-right: calc(1.5em + .75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(.375em + .1875rem) center;
    background-size: calc(.75em + .375rem) calc(.75em + .375rem);
}

And things start to become better, You can go "creative" on CSS, you could use a global approach if your style guide allows it and state that:

Every Input, when Focused (say selected by the user) and is invalid then:

input:focus:invalid {
  background: url("https://assets.digitalocean.com/labs/icons/exclamation-triangle-fill.svg") no-repeat 95% 50% lightsalmon;
  background-size: 25px;
}

this would be for each input that is detected by the browser and your css is actually loaded.