数据建模和验证方案
Schema for data modeling & validation
[![npm][npm-badge]][npm] [![GitHub Actions][actions-svg]][actions-home] [![Coverage Status][soverage-svg]][soverage]
isRequired(errorMessage?: string, trim: boolean = true)isRequiredOrEmpty(errorMessage?: string, trim: boolean = true)addRule(onValid: Function, errorMessage?: string, priority: boolean)addAsyncRule(onValid: Function, errorMessage?: string, priority: boolean)when(condition: (schemaSpec: SchemaDeclaration) => Type)check(value: ValueType, data?: DataType):CheckResultcheckAsync(value: ValueType, data?: DataType):Promiselabel(label: string)equalTo(fieldName: string, errorMessage?: string)proxy(fieldNames: string[], options?: { checkIfValueExists?: boolean })isEmail(errorMessage?: string)isURL(errorMessage?: string)isOneOf(items: string[], errorMessage?: string)containsLetter(errorMessage?: string)containsUppercaseLetter(errorMessage?: string)containsLowercaseLetter(errorMessage?: string)containsLetterOnly(errorMessage?: string)containsNumber(errorMessage?: string)pattern(regExp: RegExp, errorMessage?: string)rangeLength(minLength: number, maxLength: number, errorMessage?: string)minLength(minLength: number, errorMessage?: string)maxLength(maxLength: number, errorMessage?: string)npm install schema-typed --save…checkResult return structure is:
{
username: { hasError: false },
email: { hasError: false },
age: { hasError: true, errorMessage: 'Over the age limit' },
tags: {
hasError: true,
array: [
{ hasError: false },
{ hasError: false },
{ hasError: true, errorMessage: 'The tag should be a string' }
]
},
role: {
hasError: true,
object: {
name: { hasError: false },
permissions: { hasError: true, errorMessage: 'Permissions required' }
}
}
};StringType()
.minLength(6, "Can't be less than 6 characters")
.maxLength(30, 'Cannot be greater than 30 characters')
.isRequired('This field required');Customize a rule with the addRule function.
If you are validating a string type of data, you can set a regular expression for custom validation by the pattern method.
const model = SchemaModel({
field1: StringType().addRule((value, data) => {
return /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
}, 'Please enter legal characters'),
field2: StringType().pattern(/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/, 'Please enter legal characters')
});
model.check({ field1: '', field2: '' });
/**
{
field1: {
hasError: true,
errorMessage: 'Please enter legal characters'
},
field2: {
hasError: true,
errorMessage: 'Please enter legal characters'
}
};
**/equalTo method to verify that the values of two fields are equal.const model = SchemaModel({
password: StringType().isRequired(),
confirmPassword: StringType().equalTo('password')
});addRule method to create a custom validation rule.const model = SchemaModel({
password: StringType().isRequired(),
confirmPassword: StringType().addRule(
(value, data) => value === data.password,
'Confirm password must be the same as password'
)
});proxy method to verify that a field passes, and then proxy verification of other fields.const model = SchemaModel({
password: StringType().isRequired().proxy(['confirmPassword']),
confirmPassword: StringType().equalTo('password')
});For example, verify that the mailbox is duplicated
…Validate nested objects, which can be defined using the ObjectType().shape method. E.g:
…SchemaModel provides a static method combine that can be combined with multiple SchemaModel to return a new SchemaModel.
const model1 = SchemaModel({
username: StringType().isRequired('This field required'),
email: StringType().isEmail('Should be an email')
});
const model2 = SchemaModel({
username: StringType().minLength(7, "Can't be less than 7 characters"),
age: NumberType().range(18, 30, 'Age should be greater than 18 years old')
});
const model3 = SchemaModel({
groupId: NumberType().isRequired('This field required')
});
const model4 = SchemaModel.combine(model1, model2, model3);
model4.check({
username: 'foobar',
email: '[email protected]',
age: 40,
groupId: 1
});SchemaModel is a JavaScript schema builder for data model creation and validation.
static combine(...models)A static method for merging multiple models.
const model1 = SchemaModel({
username: StringType().isRequired('This field required')
});
const model2 = SchemaModel({
email: StringType().isEmail('Please input the correct email address')
});
const model3 = SchemaModel.combine(model1, model2);check(data: object)Check whether the data conforms to the model shape definition. Return a check result.
const model = SchemaModel({
username: StringType().isRequired('This field required'),
email: StringType().isEmail('Please input the correct email address')
});
model.check({
username: 'root',
email: '[email protected]'
});checkAsync(data: object)Asynchronously check whether the data conforms to the model shape definition. Return a check result.
const model = SchemaModel({
username: StringType()
.isRequired('This field required')
.addRule(value => {
return new Promise(resolve => {
// Asynchronous processing logic
});
}, 'Username already exists'),
email: StringType().isEmail('Please input the correct email address')
});
model
.checkAsync({
username: 'root',
email: '[email protected]'
})
.then(result => {
// Data verification result
});checkForField(fieldName: string, data: object, options?: { nestedObject?: boolean })Check whether a field in the data conforms to the model shape definition. Return a check result.
const model = SchemaModel({
username: StringType().isRequired('This field required'),
email: StringType().isEmail('Please input the correct email address')
});
const data = {
username: 'root'
};
model.checkForField('username', data);checkForFieldAsync(fieldName: string, data: object, options?: { nestedObject?: boolean })Asynchronously check whether a field in the data conforms to the model shape definition. Return a check result.
const model = SchemaModel({
username: StringType()
.isRequired('This field required')
.addAsyncRule(value => {
return new Promise(resolve => {
// Asynchronous processing logic
});
}, 'Username already exists'),
email: StringType().isEmail('Please input the correct email address')
});
const data = {
username: 'root'
};
model.checkForFieldAsync('username', data).then(result => {
// Data verification result
});Creates a type that matches all types. All types inherit from this base type.
isRequired(errorMessage?: string, trim: boolean = true)MixedType().isRequired('This field required');isRequiredOrEmpty(errorMessage?: string, trim: boolean = true)MixedType().isRequiredOrEmpty('This field required');addRule(onValid: Function, errorMessage?: string, priority: boolean)MixedType().addRule((value, data) => {
return /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
}, 'Please enter a legal character.');addAsyncRule(onValid: Function, errorMessage?: string, priority: boolean)MixedType().addAsyncRule((value, data) => {
return n暂无开放 Issues,或尚未同步最近议题。