4

I'm currently working on a web app using ASP.NET Core (C#) on the backend and Next.js (TypeScript) on the frontend. I have a lot of forms that need to be validated and I don't want to write validation rules for them twice because it will be a hell to maintain and keep them synchronized. So I want to kill two birds with one stone.

Of course, it would be easier if both frontend and backend used the same language but then I'd need to use Node or Deno instead of .NET or F# + Fable (Too esoteric to me) or even something like Blazor but it still seems too experimental to me

The only reasonable solutions I can think of:

  • Use something like JSON Schema and use it for validation on both sides (Form generators exist too):
    • Write JSON Schema myself and generate code based on that schema? (Seems like a painful route to take)
    • Generate JSON Schema from C# or TypeScript types (Something I would prefer because JSON schema seems messy and I'd prefer not to write it manually)
  • Fetch validation rules from OpenAPI somehow?
  • Use protocol buffers instead of JSON?
  • Use WebAssembly module similar to how Blazor does it but only for validation
  • Convert C# validation rules e.g. using FluentValidation to some custom format or to TypeScript code, but then you need to write your own JS library that can read it
  • Write validation logic separately for frontend and backend (Something I'm trying to avoid)

Is there anything else I can do? How do you handle it in your apps? Is there any alternative to JSON Schema you know of?

Similar question Best practice in synchronized form data validations (Web apps - Client-Server)

Konrad
  • 1,569

1 Answers1

3

Since web browser and servers run on different languages and exist in completely separate processes, there is no good way of combining these validation rules. The best you can hope for is defining as many validation rules as you can in a generic manner.

Since you are using .NET and C#, a number of validation libraries exist in C# which have some integration with the .NET Core MVC framework. This integration puts special data-val-* attributes on the form fields based on the generic validation rules in your view model. JavaScript on the client reads these attributes after moving focus away from a field or on form submit to execute the same rules on the client.

Validation rules that cannot be abstracted away in a generic validator will simply need to be run on the server. Really, all validations should be run on the server. You can forge requests using most any programming language, so don't count on JavaScript validators.

Client side validations are a convenience for the end user. Do your best to consolidate server and client side validations, but sometimes you either need to duplicate the logic, or just simply don't run those validations on the client. Only run them on the server.