Skip to content

Instantly share code, notes, and snippets.

@rinotc
Created May 21, 2022 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rinotc/97a1dd4ee1ba08a2391d84b56e28f9c9 to your computer and use it in GitHub Desktop.
Save rinotc/97a1dd4ee1ba08a2391d84b56e28f9c9 to your computer and use it in GitHub Desktop.
typescriptで値オブジェクト書いてみたサンプル
import {PreferNominal} from "../../prefer-nominal";
import * as E from "fp-ts/Either";
export class EnglishName {
// noinspection JSUnusedGlobalSymbols
readonly _englishNameBrand: PreferNominal;
constructor(readonly value: string) {
if (!EnglishName.isValid(value)) {
throw new TypeError(this.requirementErrorMessage);
}
}
private get requirementErrorMessage(): string {
return `EnglishName must between 1 to 100 length and only use alphabet or numerical, but value is "${this.value}"`;
}
equals(other: EnglishName): boolean {
return this.value === other.value;
}
static validate(value: string): E.Either<string, EnglishName> {
if (this.isValid(value)) {
return E.right(new EnglishName(value));
}
return E.left(this.validationErrorMessage);
}
static isValid(value: string): boolean {
return this.mustBe1To100Characters(value) && this.mustOnlyAlphanumerical(value);
}
static validationErrorMessage: string = '英語名は1文字以上100文字以下である必要があります';
private static mustBe1To100Characters(value: string): boolean {
return value.length >= 1 && value.length <= 100;
}
private static mustOnlyAlphanumerical(value: string): boolean {
const regex = new RegExp('^[a-zA-Z\\d]{1,100}$');
return regex.test(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment