Skip to content

Data validation in JavaScript

Last updated on March 5, 2020

The piece of writing code for data validation in JavaScript is always a crucial part of building an application.

I thought of sharing these tactics would be more beneficial. That will help them to save much cost in the future for maintaining their application.

Introduction

Whenever we encounter a situation to write up a utility that accept input from an end-user there we should definitely validate.

Ways of Data validation in JavaScript

1. Data exists?

Validation happens simply by checking whether input holds any data.

function getUser(id){ 
[A]   if(id) {
     // To continue data retrieval
   }
}

In the above code sample, line [A] allows to only when the id parameter doesn’t have null, undefined and empty string.

This way is the most convenient way of validating input data.

2. Early return

We can write the above test condition check in another hand,

if(!id) {
      // To continue data retrieval
 }

By doing so, we restrict the Javascript execution very much early if it meets the failure condition. Thus, avoid using if-else condition check.

3. Double negation check

This way we test the truthy check for the passed arguments.

What is the truthy mean??? In JavaScript, we have 6 different falsy values.

Falsy values represent, null, undefined, NAN, '', 0 and false.

The passed input is truthy only when it doesn’t have any Falsy values from the above list.

References

Published inAngularFrameworksJavaScriptReact