1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-23 23:42:56 +02:00

add schema text validators to be functions

This commit is contained in:
Ian Storm Taylor
2018-08-15 17:58:02 -07:00
parent 55f09995a3
commit 3cf62ef394
5 changed files with 61 additions and 9 deletions

View File

@@ -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

View File

@@ -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 })
}

View File

@@ -0,0 +1,25 @@
/** @jsx h */
import h from '../../helpers/h'
export const schema = {
blocks: {
paragraph: {
text: t => t === 'valid',
},
},
}
export const input = (
<value>
<document>
<paragraph>invalid</paragraph>
</document>
</value>
)
export const output = (
<value>
<document />
</value>
)

View File

@@ -0,0 +1,27 @@
/** @jsx h */
import h from '../../helpers/h'
export const schema = {
blocks: {
paragraph: {
text: t => t === 'valid',
},
},
}
export const input = (
<value>
<document>
<paragraph>valid</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>valid</paragraph>
</document>
</value>
)

View File

@@ -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))
}
},
},
},
}