I'm working on clean client validation with IClientModelValidator and customs Html Helpers to apply css style in my app.
I found and implemented this interesting example about client validation and custom DataAnnotations. ASP.Net Core MVC - Client-side validation for custom attribute
That's perfect when I use the default helper @Html.TextBoxFor(m => m.TestCurrency) !
Now I want to enable jquery-inputmask on my custom DataAnnotations. To do this I need to add some specific css class like this :
(Yes I can just add my mask class in the custom helper, but I have like 15 helpers : VEmailBoxFor, VPasswordFor, VPhoneNumberFor... by adding the class according to a custom DataAnnotation I will be albe to use just one helper, really easier to maintain )
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-cannotbered", errorMessage);
MergeAttribute(context.Attributes, "class", "currency");
}
Once again when I'm using @Html.TextBoxFor(), I found the "currency" css class in the output and the client validation works as well.
<input class="currency" data-val="true" data-val-cannotbered="Red is not allowed!" id="TestCurrency" name="TestCurrency" type="text" value="">
But, the default style is not realy nice, isn't it ?
Like I said, I created helpers to fit with bootstrap. One of them looks like :
public static IHtmlContent VTextBoxFor<TModel, TResult>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TResult>> expression, object attributes)
I add all my css class and at the end I render the text box like this :
return helper.TextBoxFor(expression, attributes);
Now my problem appears :
<input class=" validate form-control " data-val="true" data-val-cannotbered="Red is not allowed!" id="TestCurrency" name="TestCurrency" type="text" value="">
- The style looks good
- The client validation works
- But, my class "currency" is gone
Can I catch the "validation"/"html" attributes from the Expression<Func<TModel, TResult>> expression
?
Sorry for this verry long post, but It's a little bit tricky for me. I hope to be clear enough.
Thank you all