1

I have an input where I need to have a regex express validation. I have a requirement where I need to validate against a regex that allows alphanumeric and space, but not allowing space as 1st character done?

I am validating each character pressed on the input

Here what I have tried

var regEx = /^[a-zA-Z0-9]*$/;

if (event.target.value.length > 0 && event.target.value.length < 256 && regEx.test(event.target.value) === true) {
    return true
} else {
    return false
}
Pankaj Bisht
  • 986
  • 1
  • 8
  • 27
Subham
  • 420
  • 3
  • 11
  • 34

5 Answers5

2

First of all the Reg Exp needed is,
/^(?!\s)[A-Za-z0-9\s]+$/ OR /^(?!\s)[A-Z0-9\s]+$/i

Explanation:
1). ^ : expects the pattern at the beginning.
2). $ : expects pattern at the end.
3). \s : matches a space.
4). ?! : negation.(in the above pattern it indicates that the first character cannot be a space, i.e; \s)
5). [] : matches a single character.
6). + : matches one or more.
7). i : case-insensitivity flag.

Why are you calling function for each character input?
You can wait for user to submit and then validate. You can save multiple function calls.

0

Use this statement ^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$

I hope this line will helpfull for you

PrakashT
  • 883
  • 1
  • 7
  • 17
0

This should work


var regex=/^[^\s][a-zA-Z0-9\s]+$/;
return (event.target.value.length > 0 && event.target.value.length < 256 && regEx.test(event.target.value)

tit
  • 599
  • 3
  • 6
  • 25
0
^[^-\s][a-zA-Z0-9_\s-]+$

\s - whitespace ^ - negates them all

This allows all the alphanumeric characters and it will allow the space only in the middle and at the starting of the word.

I think this helps your problem.

0

Maybe:

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

Read the docs MDN

linthertoss
  • 166
  • 6