3

I have been searching for ages but can't seem to find an exact method on how to perform text input validation when building custom blocks. I saw that for TextControl inputs you can just pass the required prop but that doesn't seem to do anything ie: when I click on update or publish etc. it carries on like normal.

<TextControl
  label="Title"
  value={title}
  onChange={(title) => setAttributes({ title })}
  required
/>

The same issue would arise for RichText components as well.

3
  • 1
    TextControl has no concept of publishing or updating, or even posts, it's a 100% generic text control, you can even use it outside of WordPress. That component is unaware of the block editor by the design, and implements a dumb wrapper around text inputs for HTML with some additional helpful things. It is not a full validation suite for block attributes, much in the same way that a small plastic pipe is not a full building plumbing system. You also can't force your block to have a title, as anybody could edit the title out of the markup and you still have to handle that
    – Tom J Nowell
    Commented Aug 9, 2022 at 17:50
  • 3
    And block attributes have a type and enum validations, and for extended validation, you can use a custom JS function which will validate the input value prior to setting the specific attribute. E.g. onChange={ ( title ) => /[a-z]+/i.test( title ) && setAttributes({ title }) } (untested) .. So validate upon setting the attribute as opposed to upon saving the post.
    – Sally CJ
    Commented Aug 9, 2022 at 17:54
  • Thanks for your comments, I will have to try and get creative :) Commented Aug 17, 2022 at 8:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.