Setting dynamic regular expression

As you know, we can use the regexp validator to check if the value matches a given JavaScript regular expression. The regular expression must be a string or an instance of RegExp.

To make it simple, let's assume that the form asks user to provide a valid ISBN which can be a ISBN 10 or ISBN 13 format.

Here is the form markup:

The first two radios asks user to choose the type of ISBN. The next text field requires a valid ISBN based on the selected ISBN type.

By default, the isbn field uses the ISBN10_REGEXP for the regexp validator. How can we turn it to ISBN13_REGEXP when user picks up the ISBN 13 format?

This guide demonstrates a few ways of supporting dynamic regular expression.

Tip

This guide uses simple patterns to validate an ISBN. You can use the isbn validator which covers more patterns and also verifies the check digit as well.

Testing numbers

You can use the following sample numbers to test with examples in the next sections.

Sample Description
9971502100 A valid ISBN 10
99921-58-10-6 An invalid ISBN 10
9780306406157 A valid ISBN 13
978-0-306-40615-6 An invalid ISBN 13

Updating validator options

When user changes the ISBN type, we can use the updateValidatorOption() method to update the validator's option. Then the ISBN field need to be revalidated via the revalidateField() method:

Using the callback validator

We can use both the callback validator and regexp validator:

Since the ISBN field depends on the ISBN type, we still need to revalidate it when the type is changed:

More examples

Related validators

The following validators might be useful to you.