Skip to content

Instantly share code, notes, and snippets.

@jsparadacelis
Created March 6, 2020 15:32
Show Gist options
  • Save jsparadacelis/fbb2525e0e79d44f43814d91a9cd3f9d to your computer and use it in GitHub Desktop.
Save jsparadacelis/fbb2525e0e79d44f43814d91a9cd3f9d to your computer and use it in GitHub Desktop.
class LengthStrategy {
constructor(configField){
this.minLength = configField['minLength'];
this.maxLength = configField['maxLength'];
}
execute(value){
if (value.length < this.minLength){
return `Error, la longitud mínima debe ser ${this.minLength}`;
}else if(value.length > this.maxLength){
return `Error, la longitud máxima debe ser ${this.maxLength}`;
}
}
}
class CharacterStrategy {
constructor(configField){
this.regex = configField['regex'];
}
execute(value){
if (!value.match(this.regex)){
return "No contiene caracteres válidos";
}
}
}
class Field {
constructor(config, value) {
this.config = config;
this.errorsList = [];
this.strategyList = [];
this.value = value;
}
addStrategy(strategyObject){
this.strategyList.push(strategyObject);
}
runValidators(){
this.strategyList.forEach(
(strategy) => {
let resultFromStrategy = strategy.execute(this.value)
if (resultFromStrategy !== undefined){
this.errorsList.push(resultFromStrategy);
}
}
)
}
}
orderValue = "###############"
orderConfig = {
'maxLength': 8,
'minLength': 2,
'regex': /^[\da-zA-Z][\w\-]{1,28}[\da-zA-Z]/,
}
orderObj = new Field(orderConfig, orderValue);
orderObj.addStrategy(new LengthStrategy(orderConfig));
orderObj.addStrategy(new CharacterStrategy(orderConfig));
orderObj.runValidators();
console.log(orderObj.errorsList)
nameValue = "Juan Parada"
nameConfig = {
'maxLength': 18,
'minLength': 2,
'regex': /[a-zA-Z]/,
}
nameObj = new Field(nameConfig, nameValue);
nameObj.addStrategy(new LengthStrategy(nameConfig));
nameObj.addStrategy(new CharacterStrategy(nameConfig));
nameObj.runValidators();
console.log(nameObj.errorsList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment