Regex Validation for Multiselect Component

This took me a bit to figure out, so sharing here in case someone else is struggling to do something similar in the future.

I wanted to add Regex validation to a Multiselect Component. The only way I could figure out to do this was with the Custom Rule field for Validation.

I really only want to check newly added Custom Values (since existing options should already be valid), but I could only figure out a way to check all the selected options. Might be nice if there was a separate array of newly added Custom Values in the component though.

Here is the code:

{{ !self.value.every(v => /^(ca )?(19[5-9]\d|20[0-4]\d|2050)(\-(0?[1-9]|1[012]))?(\-(0?[1-9]|[12][0-9]|3[01]))?$/.test(v)) ? "Please enter date in the correct format" : "" }}

Abstracted:

{{ !self.value.every(v => [YOUR REGEX HERE].test(v)) ? "Your error message here" : "Your success message here" }}

It works well enough for my use case though.

I also then prevent submission of the form if there is an invalid option selected.

If anyone has a better way to accomplish this, please share!

1 Like