0

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.

4 Answers 4

2

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

\d means digits, it is equivalent to [0-9], and \w means [a-zA-Z0-9_]. Pay attention that \w includes underscore too.
1

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

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

Comments

1

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 } 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.