I have a set of validation functions which return a response code along with an error message if the validation fails. Requests can be of three types, and each of them contains a different type of values to be validated. My question is what are the options to avoid the repetitive code, particularly in the message assignment?
const Validation = (function() {
const isParameterOneLengthValid = (data) => {
return data.length >= 5 && data.length <= 10;
};
const isParameterOneValid = (data) => {
return !(/[^A-Za-z\-0-9\,\.]/.test(data));
};
const isParameterTwoLengthValid = (data) => {
return data.length >= 1 && data.length <= 5;
};
const isParameterTwoValid = (data) => {
return !(/[^0-9]/.test(data));
};
function Validation() {}
Validation.prototype.validateFirstTypeRequest= (data) => {
if (!isParameterOneLengthValid(data.parameterOne)) {
data.code = 0;
data.message = 'Length of the parameter one is invalid';
return data;
} else if (!isParameterOneValid(data.parameterOne)) {
data.resStatus = 1;
data.resMessage = 'Parameter one is invalid';
return data;
}
if (!isParameterTwoLengthValid(data.parameterTwo)) {
data.code = 3;
data.message = 'Length of the parameter two is invalid';
return data;
} else if (!isParameterTwoValid(data.parameterTwo)) {
data.resStatus = 4;
data.resMessage = 'Parameter two is invalid';
return data;
}
return data;
};
Validation.prototype.validateSecondTypeRequest= (data) => {
if (!isParameterOneLengthValid(data.parameterOne)) {
data.code = 0;
data.message = 'Length of the parameter one is invalid';
return data;
} else if (!isParameterOneValid(data.parameterOne)) {
data.resStatus = 1;
data.resMessage = 'Parameter one is invalid';
return data;
}
return data;
};
Validation.prototype.validateThirdTypeRequest= (data) => {
if (!isParameterTwoLengthValid(data.parameterTwo)) {
data.code = 3;
data.message = 'Length of the parameter two is invalid';
return data;
} else if (!isParameterTwoValid(data.parameterTwo)) {
data.resStatus = 4;
data.resMessage = 'Parameter two is invalid';
return data;
}
return data;
};
module.exports = new Validation();
return Validation;
})();