Created
January 17, 2018 16:03
-
-
Save bz0/58c1fe06275680cf9daf603d453c5206 to your computer and use it in GitHub Desktop.
typescriptでの入力バリデーション
This file contains 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 { | |
private errorMsg = { | |
'require': "入力が空です", | |
'min_length': "{$target}文字以上で入力して下さい", | |
'max_length': "{$target}文字以下で入力して下さい" | |
}; | |
public msg:any; | |
constructor(){ | |
this.msg = []; | |
} | |
public require(input:string): void{ | |
if (input === ""){ | |
this.msg.push(this.error_message()); | |
} | |
} | |
public min_length(input:string, param:{min:number}): void{ | |
if (input.length < param.min){ | |
var msg = this.error_message(); | |
msg = this.msg_replace(msg, param.min); | |
this.msg.push(msg); | |
} | |
} | |
public max_length(input:string, param:{max:number}): void{ | |
if (input.length > param.max){ | |
var msg = this.error_message(); | |
msg = this.msg_replace(msg, param.max); | |
this.msg.push(msg); | |
} | |
} | |
private error_message(): string{ | |
var call_name = this.error_message.caller.name; | |
var msg:string = ""; | |
if (call_name==="require"){ | |
msg = this.errorMsg.require; | |
}else if(call_name==="min_length"){ | |
msg = this.errorMsg.min_length; | |
}else if(call_name==="max_length"){ | |
msg = this.errorMsg.max_length; | |
} | |
return msg; | |
} | |
private msg_replace(msg:string, replace:any): string{ | |
return msg.replace(/$target/g, replace); | |
} | |
} | |
export class observer{ | |
private listeners:any; | |
private errorMsg:any; | |
public on(func:any, param:any): void { | |
this.listeners.push({func: func, param: param}); | |
} | |
public trigger(input:string): void { | |
for(var i=0; i<this.listeners.length; i++){ | |
if (typeof this.listeners[i] === "function") this.listeners[i]['func'](input, this.listeners[i]['param']); | |
} | |
this.listeners = []; | |
return this.errorMsg; | |
} | |
} | |
const valid = new validation(); | |
const input:string = ""; | |
const obsrv = new observer(); | |
obsrv.on(valid.require, {input:input}); | |
obsrv.on(valid.min_length, {input:input, min:2}); | |
obsrv.on(valid.max_length, {input:input, max:10}); | |
console.log(valid.msg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment