This page looks best with JavaScript enabled

Form Data Validation in Client and Server

 ·   ·  ☕ 2 min read

I am using Vue quite a bit and Vuelidate/ VeeValidate have spoilt me with options. The client-side validations are quite neat and easy to do. All you need is a couple of lines of code, some rules in the script section and you are good to go.

However, you should not stop at this. Validation needs to occur in the server in addition to the client for all important data.

Why -

  • Client rules are of course applicable on a form, however what if the user maliciously or playfully circumvents after resetting some variable values in browser Dev tools?
  • What if client rules don’t fire for some reason or malfunction?
  • How about your support APIs? Do you trust all your clients enough to allow whatever data that will be passed by them?

For these reasons and more it will always be better to have client validations backed up by the server.

Let us take a simple example of collecting an email. We will stick to vanilla Javascript for simplicity (though I sometimes find comfort in Vue’s simplicity, but I digress.)

HTML allows an input type of email.

1
2
3
4
5
6
7
<html>
  <h1>Beautiful Form</h1>
  <form>
    <input type="email" required /> <br /><br />
    <input type="submit" value="Submit" />
  </form>
</html>

Or, you could use RegEx with some CSS for added effect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
  <body>
    <h1>Beautiful Form</h1>

    <form>
      <input
        pattern="(?!(^[.-].*|[^@]*[.-]@|.*\.{2,}.*)|^.{254}.)([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@)(?!-.*|.*-\.)([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,15}"
        required
      />
      <br /><br />
      <input type="submit" value="Submit" />
    </form>

    <script></script>
    <style>
      input:valid {
        background-color: rgb(125, 236, 125);
      }
      input:invalid {
        background-color: rgb(231, 138, 138);
      }
    </style>
  </body>
</html>

On the client, I could either change the text type of the input box or the Regex to permit form to be submitted.

We can have server validation either in the controller or equivalent to send out an error when invalid data is received. A JS example below.

1
2
3
4
const inputEmail = "a@a.com"; // typically received from request data
const regexEmail = /(?!(^[.-].*|[^@]*[.-]@|.*\.{2,}.*)|^.{254}.)([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@)(?!-.*|.*-\.)([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,15}/;

if (!inputEmail.match(regexEmail)) throw "Email is not valid.";

You will go through the exception logic provided by your framework of course.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things