Add PATTERN Support to TEXTAREA for Validation

While unfortunate, by now it should be well-known that textarea elements do not support pattern attributes. Why W3C would omit that attribute for multiline text fields is beyond me… maybe it’s because we cannot specify flags in our patterns? 🤔

Since we really wanted our textarea to validate by pattern, and until/if such support is added to the HTML standards, we modified a basic Bootstrap Validation script to make it work with minimal changes.

Let’s say your validation code looks something like this…

document.querySelectorAll('.needs-validation').forEach(form => {
	form.addEventListener('submit', event => {
		if (!form.checkValidity()) {
			event.preventDefault()
			event.stopPropagation()
		}
		
		form.classList.add('was-validated')
	}, false)
})

And you want your textarea to be 10-500 characters.

<textarea pattern=".{10,500}" required></textarea>

Disclaimer: Yes we know minlength and maxlength attributes would achieve the same result; this is merely an example 😉

The browser considers that textarea invalid when empty since the required attribute is present. It will not however test that regular expression against the contents. So any text entered would be considered valid.

Our solution was looping over textarea fields with pattern attributes and test each regular expression before checkValidity().

form.querySelectorAll('textarea[pattern]').forEach(textarea => {
	const pattern = new RegExp(textarea.getAttribute('pattern'), 's')
	textarea.setCustomValidity(pattern.test(textarea.value) ? '' : 'Invalid')
})

Note: The “s” flag may not be required for your regular expressions.

Leave a Reply

Your email address will not be published. Required fields are marked *