A custom validation attribute in Asp.net core can be implemented by creating a class that implements ValidationAttribute, IClientModelValidator.
In that class one can code the validation rule and emmit the relevant data-val attributes.
On the JavaScript side, we need a function that performs the client side validation.
This can be archived by using .validator.addMethod(...) and $.validator.unobtrusive.adapters.add(...)
This code usually is added to the relevant .js file.
However, I would prefer to emit the javascript code from within my validation attribute. This would make sharing and reusing the attribute much easier.
Any ideas how to achive this?
ValidationAttributeis not responsible for (and cannot) generate html. That is the responsibility ofHtmlHelperorTagHelpermethods which read the metadata generated by the attribute. You could obviously write your own HtmlHelper extension methods or TagHelpers to emit script tags along with the html for the form control, but that would be a really bad idea (resulting in in-line scripts, duplicate scripts, scripts in the wrong order etc)HtmlHelperorTagHelpermethods that generate the html. For example theHtmlHelperclass has aGetUnobtrusiveValidationAttributes()method which reads the metadata of theValidationattributes applied to a property to generate thedata-val-*attributes. AValidationAttributehas no context of the type of app its being used in - it could just as well be a Windows Form app.