Yupで独自のmethodを追加する
これに対するTypeScriptの対応
例.tsyup.addMethod<yup.StringSchema>(yup.string, 'emailMax', function () {
return this.max(
validLength.EMAIL_MAX_LENGTH,
`${validLength.EMAIL_MAX_LENGTH}文字以内で入力してください`
);
});
<yup.StringSchema>
を教えてあげないと this
の内容が正しくならない
これを利用すると型エラーになる
使用側.tsyup.string().katakana();
こうする
tsdeclare module 'yup' {
interface StringSchema {
emailMax(this: StringSchema): StringSchema;
usernameMax(this: StringSchema): StringSchema;
onlyAlphaNumAndDotUnderbar(this: StringSchema): StringSchema;
notLastPeriod(this: StringSchema): StringSchema;
}
}
with this.test
tsyup.addMethod<yup.StringSchema>(yup.string, 'phoneNumber', function () {
return this.test(
'phoneNumber',
'電話番号の形式が正しくありません',
function (value) { // value :: string|null
if (value == null) return true;
const pn = new PhoneNumber(value, 'JP');
return pn.isValid();
}
);
});
this
で使えるmethodはなに?
例えば「最大の長さ」を使いまわししてaddMethodする
tsconst v = {
usernameMax: 50, // ユーザ名の最大文字数
emailMax: 100
};
(Object.keys(v) as (keyof typeof v)[]).map(key => {
yup.addMethod<yup.StringSchema>(yup.string, key, function () {
return this.max(v[key], `${v[key]}文字以内で入力してください`);
});
});
${v[key]}文字以内で入力してください
というエラーメッセージを共通して使いたいので、こういう関数を定義しておくと、あとは上の辞書に関数名と数値を指定するだけで済む