Using regex with Flatfile
A few assumptions are being made in this guide to using regular expressions with Flatfile. First, we are assuming that you are familiar with regular expressions in Javascript. Second, we are assuming that you have verified that your regular expression works as intended. If you can't definitively check off these two things, don't worry, here's a regex tester that also has some regular expression information for you. With that said, there are a few key differences between normal Javascript regular expressions and a Flatfile validators regular expressions.
- String value - Flatfile requires the regex you provide to be a string. This means that when you have your final regex to use, it will need to be provided within a string. Example:
^[0-9]*$
becomes"^[0-9]*$"
. - JSON escaped - Because your regular expression will be a string, it will also need to be JSON escaped. This means that certain characters will need to be escaped. Example:
^"*$
becomes^\"*$
. Here is a resource for learning more about JSON escaping that also comes with a tool that does it for you. - No regex flags - Many times you may want to use a regex flag within your regular expression, however, when using regex within Flatfile, these flags within your regex string aren't allowed. We have, however, created a
regexFlags
option that you can use to get the same functionality without having the flag as a part of the regex string itself. Check out how to use it here.
Below is a quick example of using the regex_matches
validator to make sure that age
is only a numerical value of a maximum of 3 digits in length.
const exampleFlatfileConfig = {
type: "Regex Example",
fields: [
{
label: "Age",
key: "age",
validators: [
{
validate: "regex_matches",
regex: "^\\d{1,3}$",
error: "Only can be number and must not be more than 3 digits in length.",
},
],
},
],
};