form validation in node.js

In a web application, a form submitted from the front end html page to the backend is very common. A validation of the form data is necessary both in the front end and backend. Assume there is already front end form validation being done using javascriopt, but ff the form is submitted a post action to a rest endpoint, a hacker can bypass the front end form validation and submit the form to the server directly with bad data. Therefore, a server side form data validation is also needed for a better security of the web application.

Assume we know exactly what kind of data the form should have, and they should be something like this.

var template = {
	"firstname": "string",
	"lastname": "string",
	"email": "string",
	"creditCard": {
		"number": "string",
		"expirationDate": "string",
		"cvv": "string"
	},
	"billingAddress": {
		"state": "string",
		"zip": "string"
	}
};

A sample form data that is missing a zip field

var formData = {
	"firstname": "Jeremy",
	"lastname": "Goldman",
	"email": "jeremy.g@test.com",
	"creditCard": {
		"number": "4111111111111111",
		"expirationDate": "09/2020",
		"cvv": "123"
	},
	"billingAddress": {
		"state": "NY",
		"zip": "12222"
	}
};

The validation function here will catch the missing zip

function validateForm(data, template) {
	var result = {"isValid": true};
	function validate(data, template) {
		for (var key in template) {
			if (template.hasOwnProperty(key)) {
				if (typeof data[key] === 'object' && typeof template[key] == 'object') {
					validate(data[key], template[key]);
				} else {
					if (typeof data[key] !== template[key]) {
						result.isValid = false;
						result.msg = key + " doesn't exist or is not of the correct type.";
						return;
					}
				}
			}
		}
	}

	validate(data, template);
	return result;
}

console.log(validateForm(formData, template));
// { isValid: false,
//   msg: 'zip doesn\'t exist or is not of the correct type.' }

Search within Codexpedia

Custom Search

Search the entire web

Custom Search