How can check a minimum 3 characters in a given value ,using regular expression
I have javascript code for checking the zipcode
var regexObj =
/^(?=[^-]*-?[^-]*$)[0-9-]*[0-9]$/;
I need to add one more condition to this,ie
make it so that user has to enter a minimum of 3 characters
Can any开发者_如何学Python one say, how can i modify my regular expression for that
/^(?=[^-]*-?[^-]*$)[0-9-]*[0-9]$/
is equivalent to
/^[0-9-]*[0-9]$/
You can add a length check in the same pass without requiring lookahead
/^[0-9-]{2,}[0-9]$/
That's a minimum of 3 characters, the last being a digit and the rest being digits and -
. See http://www.rubular.com/r/oa9wVxggz0
You might also want to restrict the first character from being a -
. You might also want to require 3 digits, without counting the -
as one of the required 3 characters. Putting these together we would get:
/^[0-9]-*[0-9][0-9-]*[0-9]$/
See http://www.rubular.com/r/Qhl843Txib
Why in the world do you need a regex to check the length of a string?
var testString1 = 'this is long enough';
alert(testString1.length >= 3); // true
var testString2 = 'no';
alert(testString2.length >= 3); // false
In HTML5, you can use a pattern.
In your example, you would do the following, where 3 is the minimum value and anything after the comma would be a maximum value (in your case, you don't have a maximum value):
<input pattern=".{3,}">
Are you sure this is for checking "ZipCode" (uniquely American)?
Wikipedia: "ZIP codes are a system of postal codes used by the United States Postal Service (USPS) since 1963. The term ZIP, an acronym for Zone Improvement Plan,[1] is properly written in capital letters and was chosen to suggest that the mail travels more efficiently, and therefore more quickly, when senders use the code in the postal address. The basic format consists of five decimal numerical digits. An extended ZIP+4 code, introduced in the 1980s, includes the five digits of the ZIP code, a hyphen, and four more digits that determine a more precise location than the ZIP code alone."
/^(\d{5})(-\d{4})?$/
精彩评论