Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add x-validator-merge prop && registerMergeRules api #4208

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/core/src/models/Field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
isArr,
} from '@formily/shared'
import {
Validator,
ValidatorTriggerType,
parseValidatorDescriptions,
} from '@formily/validator'
Expand Down Expand Up @@ -78,6 +79,7 @@ export class Field<
feedbacks: IFieldFeedback[]
caches: IFieldCaches = {}
requests: IFieldRequests = {}
validatorMerge: Record<string, Validator>
constructor(
address: FormPathPattern,
props: IFieldProps<Decorator, Component, TextType, ValueType>,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/shared/internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ export const validateToFeedbacks = async (
triggerType,
validateFirst: field.props.validateFirst ?? field.form.props.validateFirst,
context: { field, form: field.form },
validatorMerge: field.validatorMerge,
})

batch(() => {
Expand Down
5 changes: 4 additions & 1 deletion packages/json-schema/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ export const patchCompile = (
}

export const patchSchemaCompile = (
targetState: IGeneralFieldState,
targetState: IGeneralFieldState & {
schema: ISchema
},
sourceSchema: ISchema,
scope: any,
demand = false
Expand All @@ -131,4 +133,5 @@ export const patchSchemaCompile = (
patchStateFormSchema(targetState, path, compiled)
}
})
targetState['schema'] = sourceSchema
}
2 changes: 2 additions & 0 deletions packages/json-schema/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ export class Schema<
['x-display']?: Display;
//校验器
['x-validator']?: Validator;
//覆盖校验器,可以合并 全局校验 和 简写校验
['x-validator-merge']?: Record<string, Validator>;
//装饰器
['x-decorator']?: Decorator;
//装饰器属性
Expand Down
5 changes: 5 additions & 0 deletions packages/json-schema/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { isFn, each, isPlainObj, isArr, toArr, FormPath } from '@formily/shared'
import { isObservable, untracked } from '@formily/reactive'
import { Schema } from './schema'
import { ISchema } from './types'
import { registerMergeRules } from '@formily/validator'

const REVA_ACTIONS_KEY = Symbol.for('__REVA_ACTIONS')

Expand Down Expand Up @@ -36,6 +37,7 @@ export const SchemaStateMap = {
'x-display': 'display',
'x-pattern': 'pattern',
'x-validator': 'validator',
'x-validator-merge': 'validatorMerge',
'x-decorator': 'decoratorType',
'x-component': 'componentType',
'x-decorator-props': 'decoratorProps',
Expand Down Expand Up @@ -100,6 +102,9 @@ export const traverseSchema = (
schema: ISchema,
visitor: (value: any, path: any[], omitCompile?: boolean) => void
) => {
if (schema['x-validator-merge'] !== undefined) {
registerMergeRules(schema['x-validator-merge'])
}
if (schema['x-validator'] !== undefined) {
visitor(
schema['x-validator'],
Expand Down
46 changes: 46 additions & 0 deletions packages/validator/src/__tests__/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,22 @@ import {
registerValidateFormats,
setValidateLanguage,
registerValidateMessageTemplateEngine,
registerMergeRules,
} from '../index'

registerValidateRules({
custom: (value) => (value === '123' ? 'custom error' : ''),
customBool: () => false,
customBool2: () => true,
customBool3: (value) => {
return value === 'registerValidateRules'
},
})

registerMergeRules({
customBool3: (value) => {
return value === 'registerMergeRules'
},
})

registerValidateFormats({
Expand Down Expand Up @@ -531,3 +541,39 @@ test('validator order with format', async () => {
'The field value is required'
)
})

test('validator merge', async () => {
registerMergeRules({
customBool3: (value) => {
return value === 'registerMergeRules'
},
})
noError(
await validate('registerMergeRules', {
customBool3: true,
message: 'custom error',
})
)
})

/**
* @description other test case should be before this one, because it will change the default rules
*/
test('validator merge required', async () => {
registerMergeRules({})
hasError(
await validate('', [{ required: true }]),
'The field value is required'
)

registerMergeRules({
required: () => {
return true
},
})
noError(
await validate('', {
required: true,
})
)
})
54 changes: 50 additions & 4 deletions packages/validator/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,14 @@ const registry = {
language: getBrowserlanguage(),
},
formats: {},
rules: {},
rules: {
// 全局校验规则
global: {},
// 简写校验规则
easy: {},
// 自定义校验规则
merge: {},
},
template: null,
}

Expand Down Expand Up @@ -88,21 +95,60 @@ export const getValidateMessageTemplateEngine = () => registry.template
export const getValidateFormats = (key?: string) =>
key ? registry.formats[key] : registry.formats

/**
* @description 覆盖规则
* 全局规则 < 简写规则 < 用户自定义规则
* @param key
* @returns
*/
export const getValidateRules = <T>(
key?: T
): T extends string
? ValidatorFunction
: { [key: string]: ValidatorFunction } =>
key ? registry.rules[key as any] : registry.rules
: { [key: string]: ValidatorFunction } => {
let rules = {
...registry.rules['global'],
...registry.rules['easy'],
...registry.rules['merge'],
}
return key ? rules[key as any] : rules
}

export const registerValidateLocale = (locale: IRegistryLocales) => {
registry.locales.messages = deepmerge(registry.locales.messages, locale)
}

/**
* @description 全局规则
* @param rules
*/
export const registerValidateRules = (rules: IRegistryRules) => {
each(rules, (rule, key) => {
if (isFn(rule)) {
registry.rules[key] = rule
registry.rules['global'][key] = rule
}
})
}
/**
* @description 简写规则
* @param rules
*/
export const registerEasyRules = (rules: IRegistryRules) => {
each(rules, (rule, key) => {
if (isFn(rule)) {
registry.rules['easy'][key] = rule
}
})
}

/**
* @description 自定义规则
* @param rules
*/
export const registerMergeRules = (rules: IRegistryRules) => {
each(rules, (rule, key) => {
if (isFn(rule)) {
registry.rules['merge'][key] = rule
}
})
}
Expand Down
1 change: 1 addition & 0 deletions packages/validator/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,5 @@ export interface IValidatorOptions<Context = any> {
validateFirst?: boolean
triggerType?: ValidatorTriggerType
context?: Context
validatorMerge?: Record<string, Validator>
}
Loading