-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
How can I set the maxLength of characters? #3897
Comments
Take a look at Sorry about lack of code, I haven't touched my Slate codebase for few months and I'd have to look things up from docs, e.g how to listen insertion, etc. While you're at it, do the lookup yourself. Hope it helps! |
A topic like this is best discussed in the Slate Slack. Closing for now. Thanks! |
I was able to get max length using text property. No need to iterate recursively |
Posting for slack answers for vis. Example of counting length: https://codesandbox.io/s/pedantic-http-0ojcl?file=/src/App.js
(Only seems to work up to 0.72 due to slate js changes, have not checked pasted 0.72) |
@ProjectBarks this seems to limit typing new characters after a certain limit, but still allows users to paste text |
I've found the workaround. However, this method only works when you can have 1 child and text only.
|
Another way to limit characters is to use onDOMBeforeInput of Editable component const handleDOMBeforeInput = (event) => {
const inputType = event.inputType;
if (inputType === 'insertText') {
const textLength = Editor.string(editor, []).length;
if (textLength >= 20) {
event.preventDefault();
return;
}
}
}; |
I got it working by inversing the operation after I apply it and the length is greater then my defined max length for my control.
|
My solution
const withMaxLength = (editor: ReactEditor & HistoryEditor) => {
const { apply } = editor;
editor.apply = (operation) => {
const isInsertText = operation.type === 'insert_text';
const currentLength = editor.string([]).length;
const substr = MAX_LENGTH - currentLength;
if (isInsertText) {
if (substr > 0) {
operation.text = operation.text.slice(0, substr);
apply(operation);
} else {
apply(operation);
apply(Operation.inverse(operation));
}
} else {
apply(operation);
}
};
return editor;
}; |
Hi! Do you have a working solution or example how to set a limit of the characters in the editor?
The text was updated successfully, but these errors were encountered: