How to check at least 3 characters in a given value using a regular expression

I have javascript code to check zipcode

var regexObj = /^(?=[^-]*-?[^-]*$)[0-9-]*[0-9]$/; 

I need to add another condition, i.e.

make the user enter at least 3 characters

Can anyone tell how I can change my regex for this

+4
source share
4 answers
 /^(?=[^-]*-?[^-]*$)[0-9-]*[0-9]$/ 

equivalently

 /^[0-9-]*[0-9]$/ 

You can add a length check in the same pass without requiring viewing

 /^[0-9-]{2,}[0-9]$/ 

These are at least 3 characters, the last is a digit, and the rest are numbers and - . See http://www.rubular.com/r/oa9wVxggz0

You can also limit the first character to - . You can also require 3 digits, not counting - as one of the three required characters. Combining them, we get:

 /^[0-9]-*[0-9][0-9-]*[0-9]$/ 

See http://www.rubular.com/r/Qhl843Txib

+14
source

Why in the world do you need a regular expression 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 
+11
source

In HTML5 you can use a template .

In your example, you will do the following, where 3 is the minimum value and anything after the decimal point will be the maximum value (in your case, you do not have the maximum value):

 <input pattern=".{3,}"> 
+1
source

Are you sure this is for checking "ZipCode" (uniquely American)?
Wikipedia: β€œPostal Codes are a postal code system used by the United States Postal Service (USPS) since 1963. The term ZIP, an abbreviation for a zone improvement plan, [1] is spelled correctly in capital letters and was chosen to suggest that mail is sent more efficiently and therefore faster when senders use the code in the mailing address.The main format is five decimal digits. The advanced ZIP + 4 code introduced in the 1980s includes five digits. ZIP code, hyphen and four more digits which determine b Lee exact location than just the zip code. "
/^(\d{5})(-\d{4})?$/

0
source

Source: https://habr.com/ru/post/1334717/


All Articles