diff --git a/docs/reference/slate/schema.md b/docs/reference/slate/schema.md index 0afd9c2c5..a2c866333 100644 --- a/docs/reference/slate/schema.md +++ b/docs/reference/slate/schema.md @@ -233,15 +233,20 @@ Will validate a node's parent against a [`match`](#match). ### `text` -`Array` +`RegExp|Function` ```js { text: /^\w+$/ } ``` +```js +{ + text: string => string === 'valid' +} +``` -Will validate a node's text with a regex. +Will validate a node's text with a regex or function. ## Static Methods diff --git a/packages/slate/src/models/schema.js b/packages/slate/src/models/schema.js index c993a338e..607b96af3 100644 --- a/packages/slate/src/models/schema.js +++ b/packages/slate/src/models/schema.js @@ -561,7 +561,8 @@ function validateMarks(node, rule) { function validateText(node, rule) { if (rule.text == null) return const { text } = node - const valid = rule.text.test(text) + const valid = + typeof rule.text === 'function' ? rule.text(text) : rule.text.test(text) if (valid) return return fail(NODE_TEXT_INVALID, { rule, node, text }) } diff --git a/packages/slate/test/schema/custom/node-text-invalid-function.js b/packages/slate/test/schema/custom/node-text-invalid-function.js new file mode 100644 index 000000000..3d82cd3fb --- /dev/null +++ b/packages/slate/test/schema/custom/node-text-invalid-function.js @@ -0,0 +1,25 @@ +/** @jsx h */ + +import h from '../../helpers/h' + +export const schema = { + blocks: { + paragraph: { + text: t => t === 'valid', + }, + }, +} + +export const input = ( + + + invalid + + +) + +export const output = ( + + + +) diff --git a/packages/slate/test/schema/custom/node-text-valid-function.js b/packages/slate/test/schema/custom/node-text-valid-function.js new file mode 100644 index 000000000..daaf0529a --- /dev/null +++ b/packages/slate/test/schema/custom/node-text-valid-function.js @@ -0,0 +1,27 @@ +/** @jsx h */ + +import h from '../../helpers/h' + +export const schema = { + blocks: { + paragraph: { + text: t => t === 'valid', + }, + }, +} + +export const input = ( + + + valid + + +) + +export const output = ( + + + valid + + +) diff --git a/packages/slate/test/schema/custom/node-text-valid.js b/packages/slate/test/schema/custom/node-text-valid.js index c61abcc90..ae8bd9902 100644 --- a/packages/slate/test/schema/custom/node-text-valid.js +++ b/packages/slate/test/schema/custom/node-text-valid.js @@ -1,17 +1,11 @@ /** @jsx h */ -import { NODE_TEXT_INVALID } from 'slate-schema-violations' import h from '../../helpers/h' export const schema = { blocks: { paragraph: { text: /^\d*$/, - normalize: (change, { code, node }) => { - if (code == NODE_TEXT_INVALID) { - node.nodes.forEach(n => change.removeNodeByKey(n.key)) - } - }, }, }, }