Data Validation in JavaScript
Data validation is a crucial programming task that ensures data correctness. It involves checking data for validity and handling both success and failure cases. In JavaScript, using monads like Validation can simplify this process by abstracting over conditionals and providing a composable way to manage validation logic.
Overview of Data Validation
Data validation can be approached using higher-order functions and Algebraic Data Types (ADTs) such as Functor and Monad. This approach allows for composable and modular code, reducing the complexity of conditionals and improving maintainability. By using these abstractions, developers can create a closed context around the validation logic, which helps in managing the flow of data through a sequence of operations.
Handling Invalid Data
When dealing with invalid data such as null or undefined, it is essential to handle these cases without cluttering the code with conditional statements. The compose function can be used to embed validation checks before each composed function, as shown in the following listing:
Listing 5.1 Embedding validation checks before each composed function
compose(f3, validate, f2, validate, f1, validate);
function validate(data) {
if(data !== null) {
return data; // #1
}
throw new TypeError(`Received invalid data ${data}`); // #2
}
// #1 Pass the data along to the next function in the chain.
// #2 Otherwise, exit with an error.
This method ensures that each function in the composition sequence receives valid data, and any invalid data is caught early in the process.
The Validation Monad
The Validation monad is a powerful abstraction that models two states: Success and Failure. These states are central to driving a series of validations to a final result or an error. The Validation class is designed to be an abstract class, with Success and Failure as its concrete variants.
Structure of the Validation Type
Figure 5.4 Structure of the Validation type. Validation offers a choice of Success or Failure, never both.
The Success branch allows functions to be applied to the contained value when active, using methods like map and flatMap. In contrast, the Failure branch skips the logic and propagates the error encountered, which is useful for bubbling up errors during complex operations.
Implementation of Validation
The Validation class and its variants can be implemented using classes or objects. Here is an example using classes:
Listing 5.15 Parent Validation class
class Validation {
#val;
constructor(value) {
this.#val = value;
if (![Success.name, Failure.name].includes(new.target.name)) {
throw new TypeError(
`Can't directly instantiate a Validation.
Please use constructor Validation.of`
);
}
}
get() {
return this.#val;
}
static of(value) {
return Validation.Success(value);
}
static Success(a) {
return Success.of(a);
}
static Failure(error) {
return Failure.of(error);
}
get isSuccess() {
return false;
}
get isFailure() {
return false;
}
getOrElse(defaultVal) {
return this.isSuccess ? this.#val: defaultVal;
}
toString() {
return `${this.constructor.name} (${this.#val})`;
}
}
Listing 5.16 Success and Failure branches of Validation
class Success extends Validation {
static of(a) {
return new Success(a);
}
get isSuccess() {
return true;
}
}
class Failure extends Validation {
get isFailure() {
return true;
}
static of(b) {
return new Failure(b);
}
get() {
throw new TypeError(`Can't extract the value of a Failure`);
}
}
Alternative Implementation Using OLOO
An alternative to using classes is the OLOO (Objects Linked to Other Objects) pattern, which can simplify the code by removing the need for class-based syntax:
const Validation = {
init: function(value) {
this.isSuccess = false;
this.isFailure = false;
this.getOrElse = defaultVal => this.isSuccess ? value : defaultVal;
this.toString = () => `Validation (${value})`;
this.get = () => value;
return this;
}
};
const Success = Object.create(Validation);
Success.of = function of(value) {
this.init(value);
this.isSuccess = true;
this.toString = () => `Success (${value})`;
return this;
};
const Failure = Object.create(Validation);
Failure.of = function of(errorMsg) {
this.init(errorMsg);
this.get = () =>
throw new TypeError(`Can't extract the value of a Failure`);
this.toString = () => `Failure (${errorMsg})`;
return this;
};
This pattern reduces complexity by eliminating the need for private variables and class-oriented inheritance, while maintaining the same functionality.
FAQ (Frequently asked questions)
What is data validation in programming?
How can monads like Validation simplify data validation?
What is contextual data validation?
How does contextual data validation improve code?