Created
August 6, 2021 19:39
-
-
Save Abhility/ba248e5f06fda41c96f714b0166a466d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Validation { | |
constructor(data, emptyFieldErrorMesage) { | |
this.data = data; | |
this.hasErrors = false; | |
this.errors = {}; | |
this.emptyFieldErrorMesage = emptyFieldErrorMesage; | |
} | |
startValidation() { | |
return this; | |
} | |
validateEmptyFields() { | |
Object.keys(this.data).forEach((field) => { | |
if (!this.data[field].trim()) { | |
this.errors = { | |
...this.errors, | |
[field]: { | |
message: this.emptyFieldErrorMesage, | |
}, | |
}; | |
} | |
}); | |
return this; | |
} | |
validateEmail() { | |
const emailRegex = | |
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; | |
if (this.data.email) { | |
if (!this.data.email.match(emailRegex)) { | |
this.errors = { | |
...this.errors, | |
email: { | |
message: "Please provide a valid email", | |
}, | |
}; | |
} | |
} | |
return this; | |
} | |
validatePassword() { | |
const passwordRegex = | |
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; | |
if (this.data.password) { | |
if (!this.data.password.match(passwordRegex)) { | |
this.errors = { | |
...this.errors, | |
password: { | |
message: | |
"Password should be minimum 8 characters long with atleast one uppercase ,one lowercase, one number and one special character", | |
}, | |
}; | |
} | |
} | |
return this; | |
} | |
validatePasswordMatch(){ | |
if(this.data.password && this.data.confirmPassword){ | |
if(this.data.password !== this.data.confirmPassword){ | |
this.errors = { | |
...this.errors, | |
confirmPassword: { | |
message: | |
"Password and Confirm Password fields should match", | |
}, | |
}; | |
} | |
} | |
return this; | |
} | |
validateMobileNumber() { | |
if (this.data.mobile){ | |
if(this.data.mobile.length < 10){ | |
this.errors = { | |
...this.errors, | |
confirmPassword: { | |
message: | |
"Please provide valid mobile number", | |
}, | |
}; | |
} | |
} | |
return this; | |
} | |
complete() { | |
return { | |
errors: this.errors, | |
hasErrors: !!Object.keys(this.errors).length, | |
}; | |
} | |
} | |
/* Usage */ | |
const validation = new Validation(data, "This is a required field"); | |
const { hasErrors, errors } = validation | |
.startValidation() | |
.validateEmptyFields() | |
.validateEmail() | |
.validateMobileNumber() | |
.validatePassword() | |
.validatePasswordMatch() | |
.complete(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment