Question

I was unable to find correct regex for my case. I found almost perfect, but it still passes with leading spaces.

Requirements:

var regex = /^\s*(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)\s*$/;

var passwd = "abcdefg12345" //Passes
var passwd = " abcdefg12345" //Does not pass
var passwd = "abcdefg 12345" //Does not pass
var passwd = "abcdefg12345 " //Passes but should not

Any advise?

Also I would like to add minimum requirement for length, how should that be done?

Était-ce utile?

La solution

If you want to prevent leading or trailing spaces, just remove the last \s. To set a minimum length for the password, change your + quantifier to {n,}, where n is the minimum length.

For example, the following pattern matches any sequence of 5 or more alphanumeric characters that contains at least one letter, and at least one number:

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{5,})$/
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top