Home > Back-end >  React native: how to avoid double special characters?
React native: how to avoid double special characters?

Time:05-16

I have a text input which represents some title. Letters and numbers are allowed. As well as some special characters. For instance:

"Don't use" -> valid sequence
"Don''t use" -> invalid sequence
"Don'?!%^t use" -> invalid sequence
"Be quiet!" -> valid sequence
"Be quiet!><" -> invalid sequence
"123 Your name?" -> valid sequence
"123 Your name?;'" -> invalid sequence

That is if the text input contains letters, numbers and ONE character among '?! I consider my text input as valid. If the text input contains any from the other special characters OR two consecutive from the allowed special characters, I consider it as invalid.

What my regular expression should be?

I was thinking that I should probably do two tests. For instance something like:

var notAllowedCharacters = /[ `@#$%^&*()_ \-=\[\]{};:"\\|,.<>\/~]/;
if (notAllowedCharacters.test(text)) {
      //do somethin
    }

Then test again:

var alowedCharacters = /[ `'?!]/;
    //how do I test if these characers are allowed to be used only surrounded by letters?
    if (alowedCharacters.test(text)) {
      //do something
    }

Any ideas are welcome!

CodePudding user response:

If only 1 of the listed characters can occur between "words" and optionally a character except a space at the end:

^\w (?:[ `'?!]\w )*[`.?!]?$

Explanation

  • ^ Start of string
  • \w Match 1 word characters
  • (?:[ `'?!]\w )* Optionally repeat 1 of the listed characters and again 1 word characters so there can not be 2 adjacent ones.
  • [`.?!]? Optionally match 1 of the listed characters
  • $ End of string

Regex demo

const regex = /^\w (?:[ `'?!]\w )*[`.?!]?$/;
[
  "Don't use",
  "Don''t use",
  "Don'?!%^t use",
  "Be quiet!",
  "Be quiet!><",
  "123 Your name?",
  "123 Your name?;'"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));

  • Related