dwinnbrown dwinnbrown - 1 year ago 88
jQuery Question

Javascript - Ensure input has at least one number

So I have a

and am doing some front-end validation on it with jQuery and Regex.

The criteria for the input are as follows:

  • must have 5-12 characters

  • cannot contain any special characters

  • needs at least one number

it is the last point that I am struggling with.

This is how I am validating the first two criteria:

if (charsLength < 5 || charsLength > 12) {
alert("Please ensure your Unique ID is between 5 and 12 characters.");
if(/^[a-zA-Z0-9- ]*$/.test(uniqueIDContent) == false) {
alert('Your Unique ID contains illegal characters.');

Thanks in advance

Answer Source

You can add a lookahead to enforce presence of at least a digit in input:

/^(?=\D*\d)[a-zA-Z0-9 -]+$/

(?=\D*\d) is positive lookahead that asserts at least one digit is present in your field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download