CudoX
CudoX

Reputation: 1003

Javascript Validate alphanumeric with minimum text length

This script is working properly to validate alphanumeric without spaces. But how will i also include that the minimum length should be at least 3 chars?

var re = /^[A-Za-z0-9']+$/;
// Check input
if (re.test(document.getElementById(x).value)) {
    // Style green
    document.getElementById(x).style.background = '#ccffcc';
    // Hide error prompt
    document.getElementById(x + 'Error').style.display = "none";
    return true;
} else {
    // Style red
    document.getElementById(x).style.background = '#e35152';
    // Show error prompt
    document.getElementById(x + 'Error').style.display = "block";
    return false;
}

Thanks in advance.

Upvotes: 0

Views: 285

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Have you tried?

/^[A-Za-z0-9']{3,}$/;

.     (Zero or more items)
+     (One or more items)
{n}   (Exactly n items)
{n,m} (Between n and m items where n < m)

Upvotes: 2

OhleC
OhleC

Reputation: 2890

You could use an appropriate quantifier in your regular expression:

var re = /^[A-Za-z0-9']{3,}$/;

Or refactor your validation into its own function, which would be more maintainable:

var isValid = function(value) {
     var re = /^[A-Za-z0-9']+$/;
     if (!re.test(value))  { return false; }
     if (value.length < 3) { return false; }
     // further tests could go here
     return true
}

Upvotes: 1

Barmar
Barmar

Reputation: 780949

Change the regexp to:

var re = /^[A-Za-z0-9']{3,}$/;

The quantifier {min,max} means from min to max repetitions. If you leave either of them out, it means that end is unlimited, so {3,} means at least 3.

Upvotes: 0

Guffa
Guffa

Reputation: 700322

Change the + quantifier (which means one or more times) to {3,} (which means three or more times):

var re = /^[A-Za-z0-9']{3,}$/;

Upvotes: 1

Related Questions