UNPKG

@thangk/easythemer

Version:

Easily generate shades from a colour palette for use in your app

100 lines (99 loc) 2.81 kB
/** * Validate user's hex code input to make sure it's a valid hex code. * * Logic flow: * 1. check length * - len > 6, too long, error * - len < 3, too short, error * - len = 3 or 5, is # the one missing? yes: add it at front, no: error * - len = 6, is # at the front? yes: success, no: error * - success status: len = 6 wit # at front or len = 5 with no #, then add at front * * @param hexInput * @getters getResult() */ export default class validateHex { result = null; errors = false; errmsg = []; hexInput = ""; constructor(hexInput) { this.hexInput = hexInput; if (this.isLenTooLong()) this.setErrorState(); if (this.isLenTooShort()) this.setErrorState(); if (this.isLen3Or5()) this.setErrorState(); if (this.isLen6()) this.setErrorState(); this.addHashIfNeeded(); const regex = /^#([0-9A-F]{3}){1,2}$/i; if (!regex.test(this.hexInput)) { this.setErrorState(); this.addError("Hex input is not a valid hex."); return; } this.result = this.hexInput; } get getResult() { return this.result; } get isError() { return this.errors; } get errorsList() { return this.errmsg; } get getInput() { return this.hexInput; } addError(msg) { this.errmsg.push(msg); } setErrorState() { this.errors = true; } showErrors() { this.errmsg.forEach((msg) => { console.log(msg); }); } isLenTooLong() { if (this.hexInput.length > 7) { this.addError("Hex input is too long. It's not a valid hex."); return true; } return false; } isLenTooShort() { if (this.hexInput.length < 3) { this.addError("Hex input is too short. It's not a valid hex."); return true; } return false; } isLen3Or5() { if (this.hexInput.length === 3 || this.hexInput.length === 5) { if (this.hexInput[0] !== "#") { this.addError("Hex input is missing # at the front. It's not a valid hex."); return true; } } return false; } isLen6() { if (this.hexInput.length === 6) { if (this.hexInput[0] !== "#") { this.addError("Hex input is missing # at the front. It's not a valid hex."); return true; } } return false; } addHashIfNeeded() { if (this.hexInput[0] !== "#") { this.hexInput = `#${this.hexInput}`; } } }