At the moment I’ve got this:
const checkText = (t) => ({
isNotEmpty: function () {
if (t.length === 0) {
throw new Error("isNotEmpty false");
}
return this;
},
isEmail: function () {
const emailRegex = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{1,20})+$/;
if (!emailRegex.test(t)) {
throw new Error("isEmail false");
}
return this;
}
};
Using a try catch, if the text is not valid, an error is thrown and handled this way:
const isFieldValid = (email) => {
try {
const v = checkText(email)
.isNotEmpty()
.isEmail();
if (v) {
return true;
}
} catch (error) {
return false;
}
};
The goal is to short and clean the code, to avoiding the try catch, to have the final call in one line like this:
const isFieldValid = checkText('valid text').isNotEmpty().isEmail(); // one line
PS: I know there are library out there for validation. The code is an example.