The need for server-side validation


This course is focused on client side validation.

But before I move on, I want to reiterate that front-side validation is not enough. You also need to validate form data on the server (for example, with Node.js or PHP).


But why is client-side validation not enough?


3 reasons.


Reason 1: sometimes, you can only do checks on the server.


Suppose you are breeding warthogs. A user enters the number of warthogs he/she wants to purchase.

However, lets say you only have 2 warthogs left. In this case, you would want to display an error message to the user, like this:

The code for this will be something like:

if number_ordered > current_piglets then …

As you know, we get the number_ordered from the form the user filled out (on client-side).

But where does current_piglets come from?

Well, that comes from a look-up in a database. This is typical:

The server has access to the database. The browser does not.


Reason 2: security


Remember, every page a user sees in his or her browser is downloaded to his or her computer.

This includes the JavaScript that has the front-end validation code.

A clever hacker might be able to create a new version of your page, without the JavaScript checking. H/she could then fool your server into accepting invalid data.


Reason 3: Coding mistakes.


You might make a mistake coding the JavaScript. For example, you might write:

if ( username = "" ) { //WRONG!
    tell the user he needs to write a username
}
else {
    accept the data
}


The first line is wrong. It should be:

if ( username == "" ) { … }

An easy thing to miss, but it could mean that you get bad data in your databases. This can mess up sales, event registration, or whatever business your app supports.

Having a server side check doubles up as a safety net, to catch any front-size coding errors you may have written.


CONCLUSION

Even though you can do client-side validation by writing JavaScript that runs on a browser, you also need to ensure checks are done on a server, because:

  1. there are some checks you can only do on the server

  2. it improves security

  3. it helps you fix and identify front-end coding mistakes

ANYWAYS, let's get back into the topic at hand, and that is talking about the different types of client-side validation.

Keep motivated, and see you now :)