Reputation: 1003
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
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
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
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
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