How to check the input field that does not starts with '-','+','_' using yup

Viewed 31

I need to check whether the input given by the user and restrict if the field value starts with '-','+','_' using YUP validation

Thanks in advance

name: Yup.string()
    .required()
    .min(5, 'Too short')
    .matches(/^[aA-zZ\s]+$/, "Only alphabets are allowed for this field ")
    .matches()//code for checking wheather it starts with '+','-','_' if it starts I need to show an error
    

If you could jus share the regex for the following condition

  1. Minimum length 5
  2. No special characters
  3. Cannot start with '-', '_', '+'
1 Answers

The regex /^[_\-\+]{1}.*/ should match your desired inputs:

const startsWithSpecialChars = /^[_\-\+]{1}.*/;

console.log('"hello" ==> ', !!'hello'.match(startsWithSpecialChars));
console.log('"hel+lo" ==> ', !!'hel+lo'.match(startsWithSpecialChars));
console.log('"_hello" ==> ', !!'_hello'.match(startsWithSpecialChars));
console.log('"-hello" ==> ', !!'-hello'.match(startsWithSpecialChars));
console.log('"+hello" ==> ', !!'+hello'.match(startsWithSpecialChars));

The breakdown:

  • ^ indicates the start of the string
  • [_\-\+]{1} indicates exactly one character of _, -, or + (note the hyphen and plus are escaped)
  • .* indicates any number of any other character following the underscore, hyphen, or plus

As you can see, "hello" and "hel+lo" are not matched but "_hello", "-hello", and "+hello" are.

Also, for what it is worth, I'm not sure the second condition (.matches(/^[aA-zZ\s]+$/, "Only alphabets are allowed for this field ") does what you think it does and/or what it purports to do; you might consider revisiting that.

Related