-2

Im trying to build a scoreboard where you cannot input a name if it has special characters or if it contains spaces.

Tried something like this

const name = nameInput.value;
const test = /[A-z 0-9 ^\s]/.test(name)

But it doesn't work.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
relster
  • 15
  • 4
  • It would help if you tagged this with the appropriate programming language. You should also provide a minimal, complete example and explain precisely what "doesn't work" means (see https://stackoverflow.com/help/how-to-ask). – ndc85430 Dec 26 '22 at 18:52
  • You know. I honestly dont understand why i keep coming back here. This place seems to be choke full of "individuals" hellbent on having draconic rulebooks than focusing on helping people. – relster Dec 26 '22 at 19:03
  • Might have botched it when i didnt include the javascript tag (although im fairly certain regex char sets work the same for any programming language) but if you need an example for "no input if name has special character or space" then i really cant help you. – relster Dec 26 '22 at 19:04
  • What is the value of `nameInput.value;` ? – Gilles Quénot Dec 26 '22 at 19:17
  • Is it defined as well ? – Gilles Quénot Dec 26 '22 at 19:21
  • Anything a user inputs into an input bracket. The value then needs to be compared to a regex charset to ensure it does not have special characters or spaces. – relster Dec 26 '22 at 19:44
  • @hanshenrik looks like it might but it doesnt mention spaces. Will check when i get back to my laptop. Thank u – relster Dec 26 '22 at 19:46

2 Answers2

0

^ to match start and $ to match end,

/^[a-z0-9]+$/i.test("test"); => true
/^[a-z0-9]+$/i.test("test9"); => true
/^[a-z0-9]+$/i.test("test9 "); => false
/^[a-z0-9]+$/i.test("testæøå"); => false

ofc if you need unicode support, it gets a whole lot harder, not sure how to solve that.. (sure you could change the regex to /^[a-z0-9æøå]+$/iu to support Norwegian unicode characters, but that still leaves out Swedish unicode characters, you could add them but that would still leave out Chinese characters, and so on...)

  • i could make a unicode alnum table, but that would be huge, and would probably take a couple of days..
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
0

If you're ok with with an underscore (_), this should also do:

/^\w+$/.test("abiAcd9")

\w matches [A-Za-z0-9_]

Ports
  • 419
  • 2
  • 7