Can two regex be combined? Like it should match this regex or the other. Ideally exclusively (xor).
For instance, I want to validate a phone number against a landline phone number regex and a mobile phone number regex.
I wish I could do something like this but it doesn't work:
const landlinePhoneRegExp = /(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)/
const mobilePhoneRegExp = /^04[0-9 ]+/
const stripOutDelimiters = regex => etc...
const phoneRegExp = `/${stripOutDelimiters(landlinePhoneRegExp)}|${stripOutDelimiters(mobilePhoneRegExp)}/`,
UPDATE: I forgot to add that I'm using the Yup library for validation! The code looks like this:
const validationSchema = (t, i18n) => Yup.object.shape({
phone: Yup.string()
.required(t('formValidationPhoneRequired'))
.matches(localeRegex[i18n.language].phoneRegExp, t('formValidationPhoneInvalid'))
})
This explains why I was trying to dynamically combine the two regex into one like in the non-working example above.
I've been looking at the docs for a while now but there doesn't seem to be a way to do that. Maybe lazy()
would be useful but apparently I can't use string.matches()
then... unless I match (landlineMatch || mobileMatch)
to boolean(), but how could I do that?
phone: Yup.lazy((value) => {
const landlineMatch = value.match(localeRegex[i18n.language].landlinePhoneRegExp)
const mobileMatch = value.match(localeRegex[i18n.language].mobilePhoneRegExp)
return Yup.string()
.required(t('formValidationPhoneRequired'))
.matches( ??? , t('formValidationPhoneInvalid'))
})