Home > Software engineering >  Only allow this specific pattern in an input box with words starting with a pound symbol and followe
Only allow this specific pattern in an input box with words starting with a pound symbol and followe

Time:01-08

I'm trying to restrict this pattern in an input box using javascript:

#foo #bar2 #hello3 #world

Each word must start with a pound sign immediately followed by only an alphanumeric string and then a single space separating them.

I can get everything but the single space using:

/^[a-zA-Z0-9# ] $/

I'm lost on how to restrict to just a single space after each word.

let allowed = /^[a-zA-Z0-9# ] $/ 
element.on('keypress', function(e) {
    if (!allowed.test(e.key)) return false
})

CodePudding user response:

# and space should not be inside the [], since that allows them to be mixed anywhere among the letters and numbers.

# has to be before the character set, and space has to be before additional repetitions of the pattern.

let allowed = /^#[a-z0-9] (\s #[a-z0-9] )*$/;

CodePudding user response:

The regex pattern #[a-zA-Z0-9] ( #[a-zA-Z0-9] )* ? validates the input. The CSS is set to show a green input field on valid input, and a red one on invalid:

input:valid {
  background-color: palegreen;
}

input:invalid {
  background-color: lightpink;
}
<label>Tags:
<input name="tags" pattern="#[a-zA-Z0-9] ( #[a-zA-Z0-9] )* ?" />
</label>

Explanation of regex:

  • # -- literal hash sign
  • [a-zA-Z0-9] -- 1 alphanum chars
  • ( #[a-zA-Z0-9] )* -- optional additional tags, separated by a space)
  • ? -- optional space at the end (to avoid red when adding a tag)

Notes:

  • To disallow a trailing space omit the ? at the end
  • if used with a JavaScript validation instead of a pattern"" attribute you need to anchor the regex at the beginning and end: ^#[a-zA-Z0-9] ( #[a-zA-Z0-9] )* ?$
  • Related