Home > Software engineering >  Can you pass .NET backend functions to a React/Vue/etc frontend for client execution?
Can you pass .NET backend functions to a React/Vue/etc frontend for client execution?

Time:10-15

As an arbitrary example, let's say I have a login page that expects a username and password, and these fields have to pass certain validations. Let's say that the username must contain a capital 'A' and the password must be 8 characters. The frontend needs to inform the user of these validations, either locally or by asking the backend. After the user submits the form, the backend must check these validations and it does so through a function (for argument's sake) CheckLogin(form). Is it possible to pass this function to the frontend so it can run the same validations as the backend would be running without needing to ask the backend to validate the form before submission?

To be clear, obviously in this example it is trivial to add these 2 validations to the frontend as well. I am more interested if this was a large form where it would be very convenient to only have one place to change or add validations, and guarantee the validations a user would see are the same as would be run before accepting a form.

It feels like this shouldn't be possible between c# and javascript, but what about a nodeJS backend?

TLDR: Can you pass a backend form validation function to the frontend to run on client machines?

CodePudding user response:

Client-side validations can't be completely trusted and you can only be sure that the validations are correctly made if they are run in the backend.

That said, you could send your validation parameters over to the client and use your validation library of preference to implement them.

An example would be:

  1. Client requests validation parameters (let's call it GET /validations?for=situation).
  2. Server responds with validation parameters like so:
    {
      "field1": {
        "type": "string",
        "length": 8,
        "match": "some regex string",
        // ...
      },
      // ...
      "fieldN": {
        "type": "number",
        "min": 3,
        // ...
      }
    }
    
  3. Use a validation library such as yup to put your parameters to use.

Hope this helps.

  • Related