Home > Enterprise >  yup validation one character followed by other character using regular expression
yup validation one character followed by other character using regular expression

Time:06-02

I need some yup email validation rules to show some custom messages.

  1. invalid if we don't get @ followed by a .
  • abc@gmailcom (invalid)
  • def.com (invalid)

What I've tried so far: yup.string().email().matches(/^(?!\@*.)/)


  1. invalid if we get @ followed by ,
  • abc@gmail,com (invalid)

What I've tried so far: yup.string().email().matches(/^(?!\@*,)/)

None of the solutions I tried worked out.

CodePudding user response:

You can use

yup.string().email().matches(/@[^.]*\./)

and

yup.string().email().matches(/^(?!.*@[^,]*,)/)

These two regular expressions match

  • @[^.]*\. - a @ char, then zero or more chars other than . and then a . char (i.e. there must be a @ somewhere and then there must be a . to the right of the found @ char)
  • ^(?!.*@[^,]*,) - start of string (^), and then a negative lookahead ((?!...)) that fails the match if, immediately to the right of the current location, there are any zero or more chars other than line break chars as many as possible (.*), then a @, then zero or more non-comma chars ([^,]*) and then a comma. So, basically, match a string that does not contains a @ that is followed with a comma.

CodePudding user response:

One way is to write different patterns to yield different custom messages.

For example, this pattern matches a comma after the @

^[^@\s] @[^@\s,]*,

Explanation

  • ^ Start of string
  • [^@\s] Match 1 chars other than a whitespace char or @
  • @ Match literally
  • [^@\s,]*, Match optional chars other than a whitespace char or @, then match the comma

This pattern matches an email like format. It can also match a comma, but that pattern specific pattern is already being checked for.

^[^\s@] @[^\s@] \.[^\s@] $

const getMessage = s => {
  if (s.startsWith("@")) {
    return `${s} -->Invalid, string starts with @`;
  }
  if (/^[^@\s] $/.test(s)) {
    return `${s} --> Invalid, string does not contain @`;
  }
  if (/^[^@\s] @[^@\s,]*,/.test(s)) {
    return `${s} --> Invalid, string has , after @`;
  }
  if (/^[^@\s] @[^@\s.] $/.test(s)) {
    return `${s} --> Invalid, string has no . after @`;
  }
  if (/^[^\s@] @[^\s@] \.[^\s@] $/.test(s)) {
    return `${s} --> Valid format`;
  }
  return `${s} --> Invalid format`;
};
[
  "@test.com",
  "abc@gmailcom",
  "def.com",
  "abc@gmail,com",
  "[email protected]",
  "test@@"
].forEach(s => console.log(getMessage(s)));

  • Related