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)