regexp validator
Check if the value matches given JavaScript regular expression
Options
Using with form field
Name | HTML attribute | Type | Description |
---|
flags | data-fv-regexp___flags | String | If specified, flags can have any combination of JavaScript regular expression flags such as g (global match), i (ignore case), m (multiple line) |
message | data-fv-regexp___message | String | The error message |
regexp * | data-fv-regexp___regexp or pattern | String or RegExp | The JavaScript regular expression |
Look at the
Alias plugin if you want to have multiple regular expressions on the same field
Using the ES6 module
import { regexp } from '/vendors/@form-validation/cjs/validator-regexp';
const result = regexp().validate({
value: ...,
options: {
flags: ...,
message: ...,
regexp: ...,
},
});
Using the npm package
- Install the validator package:
$ npm install @form-validation/validator-regexp
- Use the
regexp
validator:
import { regexp } from '@form-validation/validator-regexp';
const result = regexp().validate({
value: ...,
options: {
flags: ...,
message: ...,
regexp: ...,
},
});
Use a correct pattern
If the validator still pass when the field value doesn't match the pattern, please ensure you use a correct pattern. Here are some check lists:
Is the pattern wrapped between ^
and $
?
For example, if a field must be 5 digits number, then ^\d{5}
(no $
at the end) is wrong pattern. ^\d{5}$
is right one.
Does the pattern work with external services?
You can use the following services to test the regular expression:
Useful patterns
The following section introduces some useful patterns:
^(?!000|666)(?:[0-6][0-9]{2}|7(?:[0-6][0-9]|7[0-2]))-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$
Traditional time in 12-hour format
^(1[0-2]|0?[1-9]):([0-5]?[0-9])$
^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$
Traditional time in 24-hour format
^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$
^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$
Numbers in a particular range
^(1[0-2]|[1-9])$
^(2[0-4]|1[0-9]|[1-9])$
^[1-5]?[0-9]$
^(3[01]|[12][0-9]|[1-9])$
^(100|[1-9]?[0-9])$
Basic example
In the following form, user is asked to enter the full name which alphabetical characters and spaces only.
HTML5 Example
When the
Declarative plugin is used, the regexp validator will be turned on automatically if the input uses HTML 5
pattern
attribute.
NPM package example
The following snippet shows how to use the regexp validator with the npm package:
import { regexp } from '@form-validation/validator-regexp';
const res1 = regexp().validate({
value: 'Ms',
options: {
regexp: /^[A-Z\s]+$/,
message: 'The input is not valid',
},
});
const res2 = regexp().validate({
value: 'form VALIDATION',
options: {
regexp: '^[A-Z\\s]+$',
flags: 'i',
message: 'The input is not valid',
},
});
See also
Changelog