0

How to validate a non required filed that should not contain the following special characters #<`> and a white space before dot(.) I have Regex \`|\#|\&|\<|\ \.|\> to validate above condition but don't have any idea how to this regex with the yup.matches(). Thanks in advance

Regex: \`|\#|\&|\<|\ \.|\> 

my validation schema is:

const validationSchema = function (values) {
  var regx = new RegExp(/\`|\#|\&|\<|\ \.|\>/gms);
    return Yup.object().shape({
      about: Yup.string()
      .matches(expression, 'about should not contain ` # < > \n')

    })
  }
Abhiram
  • 1,540
  • 1
  • 11
  • 25

2 Answers2

0

Assuming your regular expression works you could use the string.matches function. Here is the example from the documentation:

var v = string().matches(/(hi|bye)/);
v.isValid('hi')
  .should.eventually()
  .equal(true);
v.isValid('nope')
  .should.eventually()
  .equal(false);
dislick
  • 667
  • 1
  • 7
  • 25
0

See this today trying to solve same problem. I know i am late !

 return yup.object().shape(
    {
        about: yup
            .string()
            .nullable()
            .notRequired()
            .when("about", {
                // WARNING required itself => add cyclic dep at the end of the yup shape
                is: (value: string) => value?.length,
                then: (rule) => rule.matches(regx, "about should not contain ` # < > \n"),
            }),
    },
    // Add Cyclic deps here because when require itself
    [["about", "about"]]
);

Credit to this post : Yup validation for a non-required field

Please take a great care to the second parameter of the shape function. it will prevent cyclic check of the about on itself. (try it without, to see difference).

Romain TAILLANDIER
  • 1,765
  • 10
  • 18