Last active
May 9, 2019 06:14
-
-
Save hoangtranson/19ba5d6ae921ce8883ef4470beb18780 to your computer and use it in GitHub Desktop.
Namespaced Validators
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
/// <reference path="Validation.ts" /> | |
namespace Validation { | |
const lettersRegexp = /^[A-Za-z]+$/; | |
export class LettersOnlyValidator implements StringValidator { | |
isAcceptable(s: string) { | |
return lettersRegexp.test(s); | |
} | |
} | |
} |
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
/// <reference path="Validation.ts" /> | |
/// <reference path="LettersOnlyValidator.ts" /> | |
/// <reference path="ZipCodeValidator.ts" /> | |
// Some samples to try | |
let strings = ["Hello", "98052", "101"]; | |
// Validators to use | |
let validators: { [s: string]: Validation.StringValidator; } = {}; | |
validators["ZIP code"] = new Validation.ZipCodeValidator(); | |
validators["Letters only"] = new Validation.LettersOnlyValidator(); | |
// Show whether each string passed each validator | |
for (let s of strings) { | |
for (let name in validators) { | |
console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`); | |
} | |
} |
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
namespace Validation { | |
export interface StringValidator { | |
isAcceptable(s: string): boolean; | |
} | |
} |
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
/// <reference path="Validation.ts" /> | |
namespace Validation { | |
const numberRegexp = /^[0-9]+$/; | |
export class ZipCodeValidator implements StringValidator { | |
isAcceptable(s: string) { | |
return s.length === 5 && numberRegexp.test(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment