創(chuàng)建校驗(yàn)類
import { Rule, RuleType } from '@midwayjs/validate';
export class SendVerifyCodeValidator {
// 手機(jī)號(hào)
@Rule(RuleType.string().label('手機(jī)號(hào)').length(11).required())
phoneNum: string;
}
export class BindPhoneValidator {
// 手機(jī)號(hào)
@Rule(RuleType.string().label('手機(jī)號(hào)').length(11).required())
phoneNum: string;
// 驗(yàn)證碼
@Rule(RuleType.string().label('驗(yàn)證碼').length(6).required())
verifyCode: string;
}
在控制器上加上 @Validate()
即可
/**
* 綁定手機(jī)號(hào)
*/
@Post('/bindPhoneNum')
@Validate({
errorStatus: httpCodeEnum.PARAMS_ERROR,
})
async bindPhoneNum(@Body() bindPhoneData: BindPhoneValidator) {
// TODO 綁定...
return this.ok(null);
}
重點(diǎn):自定義錯(cuò)誤提示語(yǔ)
// 驗(yàn)證碼
@Rule(
RuleType.string().label('驗(yàn)證碼').length(6).required().messages({
'string.length': '{{#label}}位數(shù)錯(cuò)誤',
'string.empty': '驗(yàn)證碼不能為空',
'any.required': '驗(yàn)證碼必填',
})
)
verifyCode: string;
這么寫 是不行的!!
需要在這里去定義
@Post('/bindPhoneNum')
@Validate({
errorStatus: httpCodeEnum.PARAMS_ERROR,
validationOptions: {
messages: {
'string.length': '{{#label}}位數(shù)錯(cuò)誤',
'string.empty': '{{#label}}不能為空',
'any.required': '{{#label}}必填',
},
},
})
async bindPhoneNum(@Body() bindPhoneData: BindPhoneValidator)
但是這樣會(huì)更改所有字段的對(duì)應(yīng)異常提示
比如這個(gè)接口要校驗(yàn)手機(jī)號(hào)和驗(yàn)證碼兩個(gè)參數(shù)
當(dāng)手機(jī)號(hào)校驗(yàn)11位未通過(guò),會(huì)提示 手機(jī)號(hào)位數(shù)錯(cuò)誤
當(dāng)驗(yàn)證碼校驗(yàn)6位未通過(guò)挑秉,會(huì)提示 驗(yàn)證碼位數(shù)錯(cuò)誤
如果需要自定義驗(yàn)證器 并 提示自定義的異常信息
// 驗(yàn)證碼校驗(yàn)規(guī)則
@Rule(
RuleType.string()
.label('驗(yàn)證碼')
.required()
.custom((value, helpers) => {
const reg = /^\d{6}$/;
if (reg.test(value)) {
return value;
}
throw new Error('格式錯(cuò)誤');
})
)
verifyCode: string;
// 控制器中校驗(yàn)裝飾器
@Validate({
errorStatus: httpCodeEnum.PARAMS_ERROR,
validationOptions: {
messages: {
'any.custom': '{{#label}}{{#error.message}}',
},
},
})
// 最終響應(yīng)
{"code":5001,"message":"\"驗(yàn)證碼\"格式錯(cuò)誤"}