Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To validate alphanumeric string using regex, use /^[a-z0-9]+$/i it will handle all alphabates and numbers.

Let’s see short example of javascript regex for alphanumeric.

const regex = /^[a-z0-9]+$/i;
console.log(regex.test("hello8943"))

Today, I’m going to show you How do I check value contain only alphanumeric character in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you allow only alphanumeric character in javascript using regex?

If you want to also allow unicode character use this regex /^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/.

Here, I will show allow only alphanumeric character in javascript and typescript.

Javascript regex allow only alphanumeric character example

Here, we will create common validate function where we will validate param should alphanumeric.

function validate(param){
  const regex = /^[a-z0-9]+$/i;
  return regex.test(param);
}

// validate empty
console.log(validate(""))
// false

// validate string
console.log(validate("INFINIT"))
// true

// validate number
console.log(validate("8954"))
// true

// validate words with space
console.log(validate("infinit bility"))
// false

// validate words with hyphen
console.log(validate("infinit-bility"))
// false

Output

Typescript regex allow only alphanumeric and hyphen example

Same like javascript, we will create a function and call it with diffrent parameters.

function validate(param: string){
  const regex = /^[a-z0-9]+$/i;
  return regex.test(param);
}

// validate empty
console.log(validate(""))
// false

// validate string
console.log(validate("INFINIT"))
// true

// validate number
console.log(validate("8954"))
// true

// validate words with space
console.log(validate("infinit bility"))
// false

// validate words with hyphen
console.log(validate("infinit-bility"))
// false

Output

I hope it helps you, All the best đź‘Ť.