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.
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 thatonChange={ ( title ) => /[a-z]+/i.test( title ) && setAttributes({ title }) }
(untested) .. So validate upon setting the attribute as opposed to upon saving the post.