I am trying to create a class for Input Validation using JavaScript.
For example, the ExampleValidators class I have created:
export class ExampleValidator {
private args: any;
private errors = [];
constructor(argsz) {
this.args = argsz;
}
public required(inputName: string, customErrorMessage: string) {
if (this.hasErrors(inputName)) return this;
if (this.args.controls[inputName].value === null) {
customErrorMessage = customErrorMessage ? customErrorMessage : inputName + ' Is required';
this.addErrors(inputName, customErrorMessage);
}
return this;
}
public message(message: string) {
this.errors = [];
return this.errors = [message]
}
private addErrors(inputName: string, errorMessage: string) {
this.errors[inputName] = errorMessage;
}
private hasErrors(inputName: string) {
const errors = this.errors[inputName];
return typeof errors === 'undefined' ? false : true;
}
}
After that I tried to use the class by using a message:
private isValid() {
this.exampleValidator.required('loginDateFrom');
this.exampleValidator.required('loginDateTo').message('An example message: 02');
return this.exampleValidator.passes();
}
But after being displayed, the error appears not in specific: required ('loginDateTo'), but changes the overall error that appears.
How do I know that using 'custom message' is from reference: required ('loginDateTo'), so that the 'custom error message' has no effect on: 'required (' loginDateFrom ')?
I have tried using:
this.exampleValidator ('loginDateTo'). message ('loginDateTo', 'Some Message').
or
this.exampleValidator ('loginDateTo', 'Some Message');
It works, but I just want to try to use custom messages as I said above:
this.exampleValidator ('loginDateTo'). message ('Some Message')
How do I get a reference from the previous method: 'required' in the method: 'message'?
Or is there another way?
Thank you in advance.