First is, I want to validate the field that if the user type a character that is not existing in this (e.g.): /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/ the error message will be triggered from Yup.
Second is, I want to concatenate the 3 variables with Regex validation.
Here's the code:
const validChars1 = /[A-Za-z0-9`~!@#$%^&*()+={};:’”,./<>?| \\\\\ [\]]*$/;
const validChars2 = /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/;
const validChars3 = /[áéíóúüñ¿]/;
const mainValidator = validChars1 + validChars2 + validChars3;
const validationSchema = yup.object({
primaryInformation: yup.object({
externalEmployeeId: yup
.string()
.matches(mainValidator, "Please enter valid name")
.required(intl.get("userManagement.editor.requiredFieldError"))
//Error: Operator '+' cannot be applied to types 'RegExp' and 'RegExp'
Please help me out of this problem, thank you!
While you can't compose RegExps like this with plain JavaScript, you can do
const validChars1 = /[A-Za-z0-9`~!@#$%^&*()+={};:’”,./<>?| \\\\\ [\]]*$/;
const validChars2 = /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/;
const validChars3 = /[áéíóúüñ¿]/;
const mainValidator = new RegExp(
validChars1.source
+ validChars2.source
+ validChars3.source
);
// etc...
There is another problem with your RegExps though: the first one ends with the $ assertions that matches the end of the input. A RegExp of the form /a$b/ will never succeed because $b is contradictory. neither "a" nor "ab" can satisfy it. for "a", the $ will succeed, but the b will fail, and conversely for "ab".
If you want to compose RegExps without resorting to source string manipulation, you can have a look at compose-regexp which would let you write code like this:
import {sequence} from 'compose-regexp'
const validChars1 = /[A-Za-z0-9`~!@#$%^&*()+={};:’”,./<>?| \\\\\ [\]]*/;
const validChars2 = /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/;
const validChars3 = /[áéíóúüñ¿]/;
const mainValidator = sequence(validChars1, validChars2, validChars3);