# validator.js
```javascript=
import * as origin_yup from 'yup'
import useToast from './msgToast'
const yup = Object.assign({}, origin_yup)
// setLocale 是設定默認
yup.setLocale({
mixed: {
required: '',
},
string: {
email: '邮箱格式不符',
max: '上限${max}字',
},
})
// 寫方法
// 使用此方法是 yup.string().phone()
yup.addMethod(yup.string, 'phone', function() {
const msg = '手机号格式不符'
return this.length(11, msg).test('isNumber', msg, val => {
try {
yup.number().validateSync(val)
return true
} catch (e) {
return false
}
})
})
yup.addMethod(yup.string, 'nickname', function() {
return this.max(12)
})
yup.addMethod(yup.string, 'pwd', function() {
return this.matches(/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[A-Z])[a-zA-Z0-9]{6,12}$/, {
message: '6-12英数混合,至少1大写',
})
})
yup.addMethod(yup.string, 'pwdCheck', function(targetRef) {
return this.test('isSame', '密码不一致', function(val) {
return this.resolve(targetRef) === val
})
})
yup.addMethod(yup.string, 'qq', function() {
return this.test('isQQ', 'QQ格式不符', val => {
try {
if (!_.isEmpty(val)) {
yup
.string()
.min(7)
.max(11)
.validateSync(val)
yup.number().validateSync(val)
}
return true
} catch (e) {
return false
}
})
})
yup.addMethod(yup.string, 'wechat', function() {
return this.matches(/^[a-zA-Z]([-_a-zA-Z0-9]{6,20})+$/, {
message: '微信格式不符',
excludeEmptyString: true,
})
})
yup.addMethod(yup.string, 'name', function() {
const message = '姓名格式不符'
return this.min(2, message)
.max(6, message)
.matches(/^[\u4E00-\u9FA5]+(·[\u4E00-\u9FA5]+)*$/, {
message: '姓名格式不符',
excludeEmptyString: true,
})
})
function setHint(e, errRef) {
const msg = _.find(e.errors, i => i)
if (msg) useToast(msg)
_.each(e.inner, i => _.set(errRef, `value.${i.path}`, true))
}
// 前輩自己在yup物件底下增加的方法,原生並沒有這個方法。
// 帶入schema物件,如果不是這種類型的物件,new Error('not schema')
yup.setValidator = (schema, errRef) => {
if (!yup.isSchema(schema)) {
throw new Error('not schema')
}
const eachCall = (i, k, obj) => {
// ex: yup.object({password:string().label('密码')})
// 這時候會是 {password:{label:'密碼'}..其他種種}
if (i.fields) {
obj[k] = i.fields
_.each(i.fields, eachCall)
} else {
obj[k] = i.label
}
}
return {
validate: data => {
_.set(errRef, 'value', {})
return schema.validate(data, { abortEarly: false }).catch(e => {
setHint(e, errRef)
return Promise.reject(e)
})
},
validateSync: data => {
_.set(errRef, 'value', {})
try {
return schema.validateSync(data, { abortEarly: false })
} catch (e) {
setHint(e, errRef)
throw e
}
},
// 我們傳進來的物件是schema 。
// ex:yup.object({password:string().default('123')})
// 這時候 getDefault 就會回傳出一個物件 {password:'123'}
getDefault: () => schema.getDefault(),
// schema.describe().fields會取到我們物件的label名稱且用物件包起來
// ex: yup.object({password:string().label('密码')})
// 這時候會是 {password:{label:'密碼'}..其他種種}
// 把他理解為帶出只有label的物件 ex:{password:'密碼'}
label: _.chain(schema.describe().fields)
.cloneDeep()
.each(eachCall)
.value(),
}
}
export default yup
```