SoFunction
Updated on 2025-02-28

JS regular expression collection (detailed and practical)

Special characters in regular expressions

Character Meaning

\ As a change, the characters usually after "\" are not explained in accordance with the original meaning. For example, /b/ matches the character "b", when /\b/ is added in front of b, the change means to match the boundary of a word.
-or-
Restore the regular expression function characters, such as "*" matching it with the metacharacter before it 0 or more times, /a*/ will match a, aa, aaa, and after adding "\", /a\*/ will only match "a*".

^ Matches an input or the beginning of a line, /^a/ matches "an A", but not "An a"
$ matches the end of an input or line, /a$/ matches "An a", but not "an A"
* Match the previous metacharacter 0 or more times, /ba*/ will match b,ba,baa,baa
+ Match the previous metacharacter 1 or more times, /ba*/ will match ba,baa,baaa
? Match the previous metacharacter 0 or 1 time, /ba*/ will match b,ba
(x) Match x saves x in a variable named $1...$9
x|y matches x or y
{n} exact match n times
{n,} Match more than n times
{n,m} Match n-m times
[xyz] character set, matching any character (or metacharacter) in this set
[^xyz] does not match any character in this collection
[\b] Match a backspace character
\b Match the boundary of a word
\B Match a word's non-boundary
\cX Here, X is a control character, /\cM/ matches Ctrl-M
\d Match a character, /\d/ = /[0-9]/
\D Match a non-word numeric character, /\D/ = /[^0-9]/
\n Match a newline
\r Match a carriage return character
\s Match a whitespace character including \n,\r,\f,\t,\v, etc.
\S Matches a non-whitespace character equal to /[^\n\f\r\t\v]/
\t Match a tab character
\v Match a heavy straight tab character
\w Match a character that can form a word (alphanumeric, which is my free translation, including numbers), including underscores, such as [\w] matching 5 in "$5.98", equals [a-zA-Z0-9]
\W Match a character that cannot form a word, such as [\W] matching $ in "$5.98", equals [^a-zA-Z0-9].

The method is better to use re = new RegExp("pattern",["flags"])
pattern: regular expression
flags: g (Full text to find all patterns that appear)
i (Ignore case)
m (multiple line search)

vaScript dynamic regular expression problem

Can regular expressions be generated dynamically?
For example in JavaScript:
var str = "strTemp";
To generate:
var re = /strTemp/;
If it is a character connection:
var re = "/" + str + "/"
But to generate an expression, can it be implemented? How to implement it?


A regular expression is an object that describes character patterns.
JavaScript's RegExp objects and String objects define methods that use regular expressions to perform powerful pattern matching and text retrieval and replacement functions.

In JavaScript, regular expressions are represented by a RegExp object. Of course, a RegExp() constructor can be used to create a RegExp object.
You can also use a new special syntax added in JavaScript 1.2 to create a RegExp object. Just as a string direct quantity is defined as a character contained in quotes,
The direct quantity of the regular expression is also defined as a character contained between a pair of slashes (/). Therefore, JavaScript may contain the following code:

var pattern = /s$/;

This line of code creates a new RegExp object and assigns it to the variable parttern. This special RegExp object matches all strings ending with the letter "s". It can also be defined with RegExp()
An equivalent regular expression, the code is as follows:

var pattern = new RegExp("s$");

Whether it is using regular expressions to directly quantify or the constructor RegExp(), it is easier to create a RegExp object. The more difficult task is to use regular expression syntax to describe the pattern of characters.
JavaScript adopts a fairly complete subset of Perl regular expression syntax.

The pattern specification of regular expressions is composed of a series of characters. Most characters (including all alphanumeric characters) describe characters that match literally. In this way, regular expression /java/ matches all strings containing substring "java". Although other characters in regular expressions are not matched literally, they all have special meanings. Regular expression /s$/ contains two characters. The first special character "s" matches itself literally. The second character "$" is a special character, which matches the end of the string. Therefore, regular expression /s$/ matches a string ending with the letter "s".

1. Directly measure characters

We have found that all alphabetical characters and numbers in regular expressions match themselves literally. JavaScript's regular expressions also support certain non-alphabetical characters through escape sequences starting with a backslash (\). For example, the sequence "\n" matches a direct line break in a string. In regular expressions, many punctuation marks have special meanings. Here are the characters and their meanings:

Direct metric characters for regular expressions

Character Match
________________________________

Alphanumeric characters themselves
\ f Page break
\n Line break
\r Enter
\t Tab
\v Vertical tab
\ / One / Direct quantity
\ \ a \ direct quantity
\ . One . Direct measurement
\ * One * Direct quantity
\ + One + Direct quantity
\ ? One ? Direct quantity
\ | One | Direct quantity
\ (One (Direct quantity
\ ) One ) Direct quantity
\ [ a [ direct quantity
\ ] One ] Direct quantity
\ { a { direct quantity
\ } A } Direct quantity
\ XXX ASCII character specified by decimal number XXX
\ Xnn ASCII character specified by hexadecimal number nn
\cX control character ^X. For example, \cI is equivalent to \t, \cJ is equivalent to \n

___________________________________________________

If you want to use special punctuation marks in regular expressions, you must prefix them with a "\" .


2. Character Class

Put a separate direct characters into brackets and you can combine them into a character class. A character class matches any character it contains, so the regular expression / [abc] / matches any of the letters "a" , "b" , "c" . In addition, you can define negative character classes, which match all characters except those contained within brackets. When defining the tip of a negative character, a ^ symbol should be used as the first character calculated from the left bracket. The set of regular expressions is / [a-zA-z0-9] /.

Because some character classes are very common, JavaScript's regular expression syntax contains some special characters and escape sequences to represent these commonly used classes. For example, \s matches space characters, tab characters and other whitespace characters, while \s matches any characters other than whitespace characters.

Regular table gray-type character class

Character Match
____________________________________________________

[...] any character in brackets
[^...] any character not in brackets
. Any character except line breaks is equivalent to [^\n]
\w Any single character, equivalent to [a-zA-Z0-9]
\W Any non-single character is equivalent to [^a-zA-Z0-9]
\s Any blank sign is equivalent to [\t \n \r \f \v]
\S Any non-whitespace symbol is equivalent to [^\t\n\r\f\v]
\d Any number, equivalent to [0-9]
\D Any character except numbers is equivalent to [^0-9]
[\b] A backspace direct quantity (special case)
________________________________________________________________

3. Copy

Using the syntax of the regular table above, you can describe two digits as / \d \d / and four digits as / \d \d \d \d /. But we don't have a way to describe a number with any majority of digits or a string. This string consists of three characters and a digit following the letter. The regular expression syntax used by these complex patterns specifies the number of times each element in the expression will appear repeatedly.

The characters specified to copy always appear after the pattern in which they act. Since a certain copy type is quite common, there are some special characters specifically used to represent them. For example: The + sign matches the pattern that copies the previous pattern one or more times. The following table lists the copy syntax. Let's take a look at an example:

/\d{2, 4}/ //Match numbers between 2 and 4.

/\w{3} \d?/ //Match three single-character characters and an arbitrary number.

/\s+java\s+/ //Match the string "java" and can have one or more spaces before and after the string.

/[^"] * / //Match zero or more non-quoted characters.


Copy characters for regular expressions

Character Meaning
__________________________________________________________________

{n, m} Match the previous item at least n times, but cannot exceed m times
{n, } Match the previous item n times, or multiple times
{n} matches the previous item exactly n times
? Match the previous item 0 or 1 time, which means the previous item is optional. Equivalent to {0, 1}
+ Match the previous item 1 or more times, equivalent to {1,}
* Match the previous item 0 or more times. Equivalent to {0,}
___________________________________________________________________


4. Selection, Grouping and Reference

The syntax of regular expressions also includes specifying selections, grouping subexpressions and referring to special characters that reference the previous subexpression. Characters| are used to separate the characters to select. For example: /ab|cd|ef/ matches the string "ab", or the string "cd", or "ef". /\d{3}|[a-z]{4}/ matches either a triple digit or four lowercase letters. In regular expressions, brackets have several functions. Its main function is to divide separate items into subexpressions so that they can use *, + or ? to process those items like a single unit. For example: /java(script) ?/ matches the string "java", followed by either "script" or without. /

(ab|cd) + |ef) / The matching can be either a string "ef", or a string "ab" or "cd" one or more repetitions.

In regular expressions, the second purpose of brackets is to define sub-patterns in the complete pattern. When a regular expression successfully matches the target string, the part that matches the subpattern in parentheses can be extracted from the target string. For example, suppose that the pattern we are searching is followed by one or more letters, then we can use the pattern / [a-z] + \d+/. But since we really care about the number at the tail of each match, if we put the numeric part of the pattern in parentheses (/ [a-z] + (\d+)/) we can extract the number from any matches retrieved, and we will parse it afterwards.

Another use of subexpressions with parenthes is to allow us to reference the previous subexpression after the same regular expression. This is achieved by adding one or more digits after the string \. Numbers refer to the position of subexpressions with parenthes in the regular expression. For example: \1 refers to the subexpressions with the first parenthes. \3 refers to the subexpressions with the third parenthes. Note that since subexpressions can be nested in other subexpressions,

So its position is the position of the left bracket being counted.

For example: The following regular expression is specified as \2:
/([Jj]ava([Ss]cript)) \sis \s (fun\w*) /


The reference to the previous subexpression in a regular expression does not specify the pattern of that subexpression, but the text that matches that pattern. In this way, the reference will not only help you enter the repeating part of the regular expression quickly.

As a shortcut, it also implements a rule that each separate part of a string contains exactly the same characters. For example: the following regular expression matches all characters within single or double quotes. However, it requires a start and end quote match (for example, both are double quotes or both are single quotes):
/[' "] [^ ' "]*[' "]/


If the quotation marks of the beginning and end are required to match, we can use the following quote:
/( [' "] ) [^ ' "] * \1/


\1 matches the pattern matched by the first generation of parenthested subexpressions. In this example, it implements a rule that the beginning quotes must match the end quotes. Note that if the backslash is followed by more numbers than the parenthested subexpressions, it will be parsed into a decimal escape sequence instead of a quote. You can stick to the full three characters to represent the escape sequence, which can avoid confusion. For example, use \044 instead of \44. Here are the selection, grouping, and quoting characters for regular expressions:

Character Meaning
____________________________________________________________________

| Select. The matching is either the subexpression on the left side of the symbol or the subexpression on the right side of the symbol
(...) Grouping. Divide several items into a unit. This unit can be composed of *, +,? and | symbols, and you can also remember the characters matching this group for subsequent quotation

Use
\n matches the character matched by the nth group. The grouping is a subexpression in parentheses (possibly nested). The grouping number is the number of left-to-right counted
____________________________________________________________________

 

5. Specify the matching location

We have seen that many elements in a regular expression can match a character in a string. For example: \s match only a whitespace character. There are also elements of regular expressions that match the space with a width of 0 between characters, rather than the actual characters. For example: \b matches the boundary of a word, that is, the boundary between a /w character and a \w non-character character. Characters like \b do not specify any matching characters in a string, they specify the legal position where the match occurs. Sometimes we call these elements anchors of regular expressions because they position patterns at a specific position in the search string. The most commonly used anchor element is ^, which makes patterns depend on the beginning of the string, while the anchor element $ positions patterns at the end of the string.

For example: to match the word "javascript" , we can use the regular expression /^ javascript $/. If we want to retrieve the word "java" itself (not as prefixed in "javascript"), then we can use the pattern /\s java \s /, which requires spaces before and after the word java. But there are two problems with this. First: If "java" appears at the beginning or end of a character, the pattern will not match it unless there is a space at the beginning and end. Second: When this pattern finds a matching character, it returns a matching string with spaces at the front and back end, which is not what we want. Therefore, we use the boundary of the word \b to match the real space character \s. The result expression is /\b java \b/.

Here are the anchor characters for regular expressions:

Character Meaning
____________________________________________________________________

^ The beginning of a character is matched, and in multi-line search, the beginning of a line is matched
$ matches the end of the character, in multi-line search, matches the end of one line
\b matches the boundary of a word. In short, it is located between the characters \w and \w (note: [\b] matches the backspace character)
\B Character matching the boundary of non-words
_____________________________________________________________________


6. Properties

There is also the last element about the syntax of regular expressions, that is, the properties of regular expressions, which illustrate the rules of advanced pattern matching. Unlike other regular expression syntax, properties are described outside the / symbol. That is, they do not appear between two slashes, but are behind the second slash. Javascript 1.2 supports two properties. Attribute i indicates that pattern matching should be case-insensitive. Attribute g indicates that pattern matching should be global.

That is to say, all matches in the retrieved string should be found. These two properties can perform a global, case-insensitive match.

For example: To perform a size-insensitive search to find the first specific value of the word "java" (or "java" , "JAVA" etc.), we can use the size-insensitive regular expression /\b java\b/i . If we want to find all the specific values ​​of "java" in a string, we can also add the property g, that is /\b java \b/gi .

The following are the properties of the regular expression:


Character Meaning
_________________________________________

i perform case-insensitive matching
g performs a global match, in short, it is to find all matches, rather than stopping after finding the first one
_________________________________________

Apart from the properties g and i, regular expressions have no other properties like properties. If the static property multiline of the constructor RegExp is set to true, then pattern matching will be performed in a multi-line pattern. In this mode, the anchor characters ^ and $ match not only the beginning and end of the string, but also the beginning and end of a line inside the string. For example: pattern /Java$/ matches "Java", but does not match

"Java\nis fun" . If we set the multiline property, the latter will also be matched:

= true;

In JAVASCRIPT, determine whether a string is in the format of an email:

Copy the codeThe code is as follows:

if(!=(/^\w +[@]\w +[.][\w.] +$/))
{
alert("Your email format is wrong!");
();
return false;
}


[RED]function dateVerify(date){
var reg = /^(\d{4})(-)(\d{2})\2(\d{2})$/;
var r = (reg);
if(r==null) return false;
var d= new Date(r[1], r[3]-1,r[4]);
var newStr=()+r[2]+(()+1)+r[2]+();
date=r[1]+r[2]+((r[3]-1)+1)+r[2]+((r[4]-1)+1);
return newStr==date;
}[/RED]


17 regular expressions for javascript

"^\\d+$"//Non-negative integer (positive integer + 0)
"^[0-9]*[1-9][0-9]*$"//Positive integer
"^((-\\d+)|(0+))$"//Non-positive integer (negative integer + 0)
"^-[0-9]*[1-9][0-9]*$"//Negative integer
"^-?\\d+$"//Integer
"^\\d+(\\.\\d+)?$"//Non-negative floating point number (positive floating point number + 0)
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]+)|([0-9]*[1-9][0-9]*))$"//Positive floating point number
"^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$"//Non-positive floating point number (negative floating point number + 0)
"^(-((([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]+)|([0-9]*[1-9][0-9]*)))$"//Negative floating point number
"^(-?\\d+)(\\.\\d+)?$"//Floating point number
"^[A-Za-z]+$"//A string composed of 26 English letters
"^[A-Z]+$"//A string composed of 26 English letters capitalization
"^[a-z]+$"//A string composed of 26 English letters lowercase
"^[A-Za-z0-9]+$"//A string composed of numbers and 26 English letters
"^\\w+$"//A string composed of numbers, 26 English letters or underscores
"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"//email address
"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$"//url

Properties and methods of regular expression objects

Predefined regular expressions have the following static properties: input, multiline, lastMatch, lastParen, leftContext, rightContext and $1 to $9. where input and multiline can be preset. The values ​​of other attributes are assigned different values ​​according to different conditions after executing the exec or test method. Many attributes have two names of long and short (perl style), and these two names point to the same value. (JavaScript simulates the regular expression of perl)

Properties of regular expression objects

Attribute Meaning
$1...$9 If they exist, they are matching substrings
$_ See input
$* See multiline
$& See lastMatch
$+ See lastParen
$` See leftContext
$'' See rightContext
constructor Creates a special function prototype of an object
Whether global matches the entire string (bool type)
ignoreCase Whether to ignore case (bool type) when matching
input matched string
lastIndex The last matched index
lastParen The last substring enclosed in brackets
leftContext The last time it matches the left substring
Whether multiline is used for multiline matching (bool type)
prototype allows additional attributes to objects
rightContext The last time the right substring matches
source regular expression pattern
lastIndex The last matched index
 

Methods of regular expression objects
Method Meaning
compile regular expression comparison
exec performs search
test to match
toSource Returns the definition of a specific object (literal representation) whose value can be used to create a new object. The overload method is obtained.
toString Returns the string of a specific object. The overload method is obtained.
valueOf Returns the original value of a specific object. Overload method to obtain

example

Copy the codeThe code is as follows:

<script language = "JavaScript">
var myReg = /(w+)s(w+)/;
var str = "John Smith";
var newstr = (myReg, "$2, $1");
(newstr);
</script>

Will output "Smith, John"

JavaScript regular expression test
Copy the codeThe code is as follows:

//Check whether it is all composed of numbers
function isDigit(s)
{
var patrn=/^[0-9]{1,20}$/;
if (!(s)) return false
return true
}

//Check the login name: Only 5-20 strings starting with letters and can be included with numbers, "_", "."
function isRegisterUserName(s)
{
var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
if (!(s)) return false
return true
}

//Check user name: Only 1-30 strings starting with letters can be entered
function isTrueName(s)
{
var patrn=/^[a-zA-Z]{1,30}$/;
if (!(s)) return false
return true
}

//Check password: Only 6-20 letters, numbers, and underscores can be entered
function isPasswd(s)
{
var patrn=/^(\w){6,20}$/;
if (!(s)) return false
return true
}

//Calculate the normal telephone and fax numbers: it can start with "+", except for the number, it can contain "-"
function isTel(s)
{
//var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/;
var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
if (!(s)) return false
return true
}

//Calculate the mobile phone number: It must start with a number, except for the number, it can contain "-"
function isMobil(s)
{
var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
if (!(s)) return false
return true
}

//Check the postal code
function isPostalCode(s)
{
//var patrn=/^[a-zA-Z0-9]{3,12}$/;
var patrn=/^[a-zA-Z0-9 ]{3,12}$/;
if (!(s)) return false
return true
}

//Check search keywords
function isSearch(s)
{
var patrn=/^[^`~!@#$%^&*()+=|\\\][\]\{\}:;'\,.<>/?]{1}[^`~!@$%^&()+=|\\\][\]\{\}:;'\,.<>?]{0,19}$/;
if (!(s)) return false
return true
}

function isIP(s) //by zergling
{
var patrn=/^[0-9.]{1,20}$/;
if (!(s)) return false
return true
}


Regular expression regular expression details (I)

Regular expressions are regular expressions. It seems that English is much easier to understand than Chinese, which is to check the expression characters.
Not comply with regulations! ! Regex has a very powerful and complex object RegExp, which is provided in JavaScript 1.2 or above.

Let's take a look at the introduction to regular expressions:
Regular expression objects are used to standardize a standard expression (that is, the expression character does not meet specific requirements, such as whether it is the Email address format, etc.), and it has properties and methods used to check whether the given string complies with the rules.

In addition, the properties of individual regular expression objects you create with the RegExp constructor have already predefined the static properties of the regular expression objects, and you can use them at any time.

Core Objects:
Provided in JavaScript 1.2, NES 3.0 or above.
ToSource method has been added in JavaScript 1.3 and later versions.

Establishment method:
Text format or RegExp constructor function.
Text creation format uses the following format:
/pattern/flags i.e./mode/mark

The constructor function method is used as follows:
new RegExp("pattern"[, "flags"]) means new RegExp("pattern"[,"mark"])

parameter:
pattern(mode)
Text that represents regular expressions

flags(mark)
If you specify this, flags can be one of the following values:
g: global match (full match)
i: ignore case (ignore case)
gi: both global match and ignore case (match all possible values, and ignore case)

Note: The parameters in text format should not be marked with quotes, while the parameters of the constructor function should be marked with quotes. So the following expression creates the same regular expression:
/ab+c/i
new RegExp("ab+c", "i")

describe:
When using constructors, it is necessary to use normal strings to avoid rules (include leading characters\ in the string).
For example, the following two statements are equivalent:
re = new RegExp("\\w+")
re = /\w+/

The following provides a complete list and description of the special characters that can be used in regular expressions.

Table 1.3: Special characters in regular expressions:

character\
Meaning: For characters, it usually means literally, indicating that the next character is a special character, and is not explained.
For example: /b/ matches the character 'b'. By adding a backslash\, that is, /\b/, the character becomes a special character, indicating the dividing line matching a word.

or:
For several characters, the description is usually special, indicating that the following characters are not special, but should be interpreted literally.
For example: * is a special character that matches any character (including 0 characters); for example: /a*/ means matching 0 or more a.
To match the literal *, add a backslash before a; for example: /a\*/match 'a*'.

Character^
Meaning: The character that indicates that the matching must be at the front.
For example: /^A/ does not match 'A' in "an A," but matches 'A' in "An A."

Character $
Meaning: Similar to ^, matching the last character.
For example: /t$/ does not match 't' in "eater", but match 't' in "eater".

character*
Meaning: Match * 0 or n times before the characters.
For example:/bo*/ matches 'boooo' in "A ghost booooed" or 'b' in "A bird warbled", but does not match any characters in "A goat grunted".

Character +
Meaning: Match the characters before the + sign 1 or n times. Equivalent to {1,}.
For example: /a+/ matches all 'a' in "candy" and "caaaaaaandy."

character?
Meaning: Match? 0 or 1 previous character.
For example: /e?le?/matches 'el' in "angel" and 'le' in "angle."

character.
Meaning: (decimal point) matches all individual characters except line breaks.
For example: /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but does not match 'nay'.

Characters (x)
Meaning: Match 'x' and record the matching value.
For example: /(foo)/Match and record 'foo' in "foo bar." The matching substring can be returned by the element [1], ..., [n] in the result array, or by the attributes $1, ..., $9 of the RegExp object.

Character x|y
Meaning: Match 'x' or 'y'.
For example: /green|red/ matches 'green' in "green apple" and 'red' in "red apple."

Character {n}
Meaning: n here is a positive integer. Match the previous n characters.
For example: /a{2}/ does not match 'a' in "candy," but matches all 'a' in "caandy," and the first two in "caaandy."
'a'。

Character {n,}
Meaning: n here is a positive integer. Match at least n preceding characters.
For example: /a{2,} does not match 'a' in "candy", but matches all 'a' in "caandy" and all 'a' in "caaaaaaandy."

Character {n,m}
Meaning: n and m here are both positive integers. Match at least n at most m previous characters.
For example: /a{1,3}/ does not match any character in "cndy", but matches the first two in "candy,"
'a' and the first three 'a' in "caaaaaaandy", note: Even if there are many 'a' in "caaaaaandy", it only matches the first three 'a', i.e. "aaa".

Characters [xyz]
Meaning: a list of characters, matching any character listed. You can point out a character range by hyphen.
For example: [abcd] is the same as [a-c]. They match 'b' in "brisket" and 'c' in "ache".

Characters [^xyz]
Meaning: One-character complement, that is, it matches everything except the listed characters. You can use hyphen - point out a character range.
For example: [^abc] and [^a-c] are equivalent, they first match 'r' in "brisket" and 'h' in "chop."

Characters [\b]
Meaning: Match a space (not to be confused with \b)

Character\b
Meaning: Match the dividing line of a word, such as a space (not to be confused with [\b])
For example: /\bn\w/ matches 'no' in "noonday", /\wy\b/ matches 'ly' in "possibly yesterday."

Character\B
Meaning: Match a word's non-dividing line
For example: /\w\Bn/ matches 'on' in "noonday", /y\B\w/ matches 'ye' in "possibly yesterday."

Characters\cX
Meaning: The X here is a control character. Match a string of control characters.
For example: /\cM/ matches control-M in a string.

Character\d
Meaning: Matching a number is equivalent to [0-9].
For example: /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."

Characters\D
Meaning: Match any non-digit, equivalent to [^0-9].
For example: /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."

Character\f
Meaning: Match a form character

Character\n
Meaning: Match a newline

Characters\r
Meaning: Match a carriage return

Characters\s
Meaning: Match a single white space character, including space, tab, form feed, line feed, equivalent to [ \f\n\r\t\v].
For example: /\s\w*/ matches 'bar' in "foo bar."

Characters\S
Meaning: Matching a single character other than the white space character is equivalent to [^ \f\n\r\t\v].
For example: /\S/\w* matches 'foo' in "foo bar."

Characters\t
Meaning: Match a tab character

Character\v
Meaning: Match a header tab

Characters\w
Meaning: Match all numbers and letters and underscores, equivalent to [A-Za-z0-9_].
For example: /\w/ matches 'a' in "apple," , '5' in "$5.28," and '3' in "3D."

Character\W
Meaning: Matching other characters except numbers, letters and underscores is equivalent to [^A-Za-z0-9_].
For example: /\W/ or /[^$A-Za-z0-9_]/match '%' in "50%.".

Character\n
Meaning: n here is a positive integer. Matches the value of n of the last substring of a regular expression (counting the left bracket).

For example: /apple(,)\sorange\1/ matches 'apple, orange' in "apple, orange, cherry, peach." There is a more complete example below.
Note: If the number in the left parentheses is smaller than the number specified by \n, then the octal escape of the next row is taken as the description.

Characters\ooctal and\xhex
Meaning: Here \ooctal is an octal escape value, while \xhex is a hex escape value that allows the ASCII code to be embedded in a regular expression.


When an expression is checked, literal symbols provide a way to edit regular expressions. Using literal symbols can keep regular expressions as constants. For example, if you use literal notation in a loop to construct a regular expression, the regular expression does not need to be compiled repeatedly.

Regex object constructors, for example, new RegExp("ab+c"), provide runtime compilation of regular expressions. When you know that the pattern of a regular expression will change, you should use the constructor, or you don't know the pattern of the regular expression, but they are obtained from another source, such as when input by the user. Once you have defined the regular expression, the regular expression can be used anywhere and can be changed, and you can use the compilation method to compile a new regular expression for reuse.

A separate predefined RegExp object can be used in each window; that is, each separate JavaScript thread runs to obtain its own RegExp object. Because each script is not interruptible in one thread, this ensures that different scripts do not overwrite the value of the RegExp object.

The predefined RegExp object contains static properties: input, multiline, lastMatch, lastParen, leftContext, rightContext, and from $1 to $9. The input and multiline properties can be preset. The values ​​of other static properties are set after executing the exec and test methods of individual regular expression objects, and after executing the match and replace methods of the string.

property
Note that several properties of the RegExp object include both long and short names (like Perl). These names all point to the same value. Perl is
A programming language, and JavaScript mimics its regular expressions.

Attributes $1, ..., $9
Get the matching substring, if any

Attribute $_
Reference input

Attribute $*
Reference multiline

Attribute $&
Refer to lastMatch

Attribute $+
Reference lastParen

Attribute $`
Refer to leftContext

Attribute $'
Reference rightContext

Property constructor
Specifies to create object prototype letters

Attribute global
Decide whether to test whether a regular expression cannot match all strings, or just conflict with the first one.

Property ignoreCase
Decide whether to ignore case when trying to match a string

Attribute input
When the regular expression is matched, it is the opposite string.

Properties lastIndex
Decide on the next match from where

Properties lastMatch
The last matching character

Properties lastParen
When the substring matches, the last parenthesized, if any.

Property leftContext
Substring before the last match.

Attribute multiline
Whether to search in multiple lines of string.

Prototype
Allows append attributes to all objects

Property rightContext
The substring after the last match.

Attribute source
Pattern text

method
compile method
Compile a regular expression object

exec method
Run regular expression matching

Test method
Test regular expression matching

toSource method
Returns an object's literal description of the specified object; you can use this value to create a new object. Don't consider it
source method.

toString method
Returns a string description of the specified object, regardless of the object.

valueOf method
Returns the original value of the specified diagonal. No method is considered.

In addition, this object inherits the object's watch and unwatch methods


example:
Example 1. The following example script uses the replace method to convert words in the string. In the replaced text, the script uses the values ​​of the $1 and $2 properties of the global RegExp object. Note that when passed as a second parameter to replace method, the name of the $ attribute of the RegExp object.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=(re,"$2, $1");
(newstr)
</SCRIPT>

Show result: "Smith, John".

Example 2. In the following example script, the Change event processing handle is set. In the getInfo function, the exec method
Use the value as its parameter, note that RegExp presets the $ attribute.


<SCRIPT LANGUAGE="JavaScript1.2">
function getInfo(abc)
{
re = /(\w+)\s(\d+)/;
();
(RegExp.$1 + ", your age is " + RegExp.$2);
}
</SCRIPT>

Please enter your last name and age, and press Enter after entering.
<FORM><INPUT TYPE="TEXT" NAME="NameAge" onChange="getInfo(this);"></FORM>
</HTML>


$1, ..., $9 attributes
Match substrings enclosed in parentheses, if any.
It is the property of RegExp
Static, read only

Provided in JavaScript 1.2, NES 3.0 or above
Description: Because input is a static property, not an attribute of individual regular expression objects. You can access this property using .

The number of substrings that can be added with parentheses is not limited, but regular expression objects can only retain the last 9. If you want to access all matching strings in parentheses, you can use the returned array.

These properties can be used in the character string after the method is replaced (output result). When using this method, you do not need to consider the RegExp object in advance. An example is given below. When the regular expression does not contain parentheses, the script is interpreted as the literal meaning of $n. (N here is a positive integer).

For example:
The following script uses the replace method to exchange the positions of words in the string. In the replaced text string, the script uses regular expressions
Values ​​of the $1 and $2 properties of the RegExp object. Note: When they pass parameters to replace method, the $ attribute is not considered here
The name of the RegExp object.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=(re,"$2, $1");
(newstr)
</SCRIPT>
The output results displayed are: Smith, John.


Regular expression regular expression details (II)

Detailed description of regular expressions (II)

The following new objects that are not regular expressions are added, please refer to the properties of the corresponding JavaScript object $_ attribute Reference input $* attribute

Reference multiline $&properties Reference lastMatch $+properties Reference lastParen $`properties

Reference leftContext $' property Reference rightContext compile method Compile regular expression objects during script run
Methods belonging to RegExp are provided in JavaScript 1.2, NES 3.0 or above. Syntax:
(pattern[, flags]) In number: regexp The name of the regular expression, which can be a variable name or a literal string.
pattern The definition text of a regular expression. flags, if specified, can be one of the following: "g": Match all possible strings
"i": Ignore case "gi": Match all possible strings and ignore case Description:
Use the compile method to compile a regular expression created with the RegExp constructor function. so
It forces the regular expression to be compiled only once, not once every time the regular expression is encountered. When you confirm that the regular expression can
When it remains the same, you can use the compile method to compile it (after getting its matching pattern), so that you can use it repeatedly in the script.
You can also use the compile method to change the regular expression during runtime. For example, if the regular expression changes,
You can use the compile method to recompile the object to improve usage efficiency.
Using this method will change the values ​​of the source, global and ignoreCasesource properties of the regular expression. constructor
Point out the function to create the object prototype. Note that the value of this property is provided by the function itself, not by a string containing RegExp.
ECMA version ECMA-262 is provided in JavaScript 1.1, NES 2.0 or above. Description: Reference.
exec method Runs a matching search on the specified string. Returns an array of results. Is RegExp's method
Syntax provided in JavaScript 1.2, NES 3.0 or above: ([str])regexp([str])

Parameters: regexp, the name of the regular expression, can be a variable name or a literal definition string.
str, to match the string of the regular expression, if omitted, the value will be used.

Description: Just like in the syntax description, the exec method of the regular expression work can be called directly (using (str)) or indirectly (using regexp(str)).
If you just run to find out if it matches, you can use the String search method.
If the match is successful, the exec method returns an array and updates the value of the regular expression object property and the predefined regular expression object, RegExp. If the match fails, the exec method returns null.

Please see the following example: <SCRIPT LANGUAGE="JavaScript1.2"> //Match one b followed by one or more d, and then a b
//Ignore case myRe=/d(b+)(d)/ig; myArray = ("cdbBdbsbz");
</SCRIPT> The following is the return value of the script: Object Properties/Index Description Example
myArray

Contents of myArray ["dbBd", "bB", "d"]
index
Match index 1 based on 0
input
Original string cdbBdbsbz
[0]
The last matching character dbBd
[1], ...[n]
Match strings enclosed in parentheses, if any. There is no limit on the number of brackets. [1] = bB
[2] = d
myRe
lastIndex
The index value of the next match operation is 5
ignoreCase
Indicates whether "i" is used to ignore case true
global
Indicates whether to use the "g" tag to match all possible strings true
source
Text string that defines the pattern d(b+)(d)
RegExp
lastMatch$&
The last matching character dbBd
leftContext$\Q
The latest matches the previous substring c
rightContext$'
The latest match is followed by the substring bsbz
$1, ...$9
Match substrings in parentheses, if any. The number of brackets is not limited, but RegExp can only retain the last 9 $1 = bB
$2 = d
lastParen $+
The last matched substring with parentheses, if any

If your regular expression uses the "g" tag, you can use the exec method multiple times to continuously match the same string. When you do this, the new match will start from a substring determined by the lastIndex property value of the regular expression. For example, suppose you use the following script:

<SCRIPT LANGUAGE="JavaScript1.2"> myRe=/ab*/g;str = "abbcdefabh"
myArray = (str);
("Found "+myArray[0]+". Next match starts at "+)
mySecondArray = (str);
("Found "+mySecondArray[0]+". Next match starts at "+)
</SCRIPT>

This script displays the following results: Found abb. Next match starts at 3
Found ab. Next match starts at 9 Example:

In the following example, the user enters a name and the script performs a matching operation based on the input. Then check the array to see if it matches the names of other users.
This script assumes that the registered user's last name has been stored in array A and may be obtained from a database.

<HTML>
<SCRIPT LANGUAGE="JavaScript1.2"> A = ["zhao","qian","sun","li","liang"]
function lookup() { firstName = /\w+/i(); if (!firstName)
( + "Illegal input"); else { count=0;
for (i=0;i Enter your last name and press Enter.
<FORM><INPUT TYPE:"TEXT" NAME="FirstName" onChange="lookup(this);"></FORM>
</HTML>

global attribute Whether the "g" tag is used in the regular expression. RegExp attribute, read only
Provided in JavaScript 1.2, NES 3.0 or above Description: global is an attribute of an individual regular expression object
If the "g" tag is used, the global value is true; otherwise it is false. The "g" tag specifies that the regular expression tests all possible matches.
You can't change the value of the property directly, but you can call the compile method to change it. ignoreCase Checks whether the regular expression uses the "i" tag
RegExp attribute, read-only provided in JavaScript 1.2, NES 3.0 or above. Description:
ignoreCase is an attribute of individual regular expression objects.
Return true if the "i" tag is used, otherwise return false. The "i" mark indicates that case is ignored when matching is made.
You can't change the value of the property directly, but you can change it by calling the compile method input indicating which string to test for the regular expression. $_ is another name for this property.
RegExp's properties, statically provided in JavaScript 1.2, NES 3.0 or above

Description: Because input is static, it is not a property of a certain regular expression object. You can also use .
If no string is provided to the exec or test method of the regular expression, and there is a value in it, then use its value to call the method.
Scripts or browsers can preset input properties. If the value is preset and the exec or test method is called, no string is provided
Then use the input value when calling exec or test. Input can be set by the browser in the following way:
When the text form field processing handle is called, input is set to the string input to the text.
When the textarea form field processing handle is called, input is set to the string entered in the textarea field. Pay attention to multili
ne is also set to true to match multiple lines of text. When the select form field processing handle is called, the input is set to the value of the selected text.
When the processing handle of the link object is called, input is set to a string between <A HREF=...> and </A>.
After the event processing handle is completed, the value of the input property is cleared. lastIndex A readable/writable integer property indicating where the next match starts.
The properties of RegExp are provided in JavaScript 1.2, NES 3.0 or above

Description: lastIndex is an attribute of an individual regular expression object. This property is set only when the "g" tag of the regular expression is used for full string matching. Implement the following rules:

If the lastIndex size string length, and the lastIndex is set to 0.

If lastIndex is equal to the length of the string and the regular expression matches an empty string, the regular expression starts to match from the position of lastIndex.

If lastIndex is equal to the length of the string and the regular expression does not match the empty string, the regular expression does not match the input and lastIndex is set to 0.

Otherwise, lastIndex is set to the next point of the last match. For example, execute the script in the following order: re = /(hi)?/g Match empty strings
re("hi") returns ["hi", "hi"], and lastIndex is set to 2
re("hi") returns [""], an empty array, and its subscript 0 element is the matching string. In this case, return empty
The string is because lastIndex is equal to 2 (and still is 2), and the length of "hi" is also 2. lastMatch matches the string for the last time, $& means the same.
RegExp's properties, static, read-only, provided in JavaScript 1.2, NES 3.0 or above

Description: Because lastMatch is static, it is not an attribute that specifies a regular expression individually. You can use it too. lastParen
The matching string with brackets last time, if any. $+ means the same. RegExp attribute, static, read-only
Provided in JavaScript 1.2, NES 3.0 or above

Description: Because lastParen is static, it is not a certain regular property, you can use . to express the same meaning.
leftContext The last time that matches the previous substring, $` has the same meaning. RegExp's properties, static, read-only
Provided in JavaScript 1.2, NES 3.0 or above

Description: Because leftContext is static and not a property of a certain regular expression, it can be used to express the same meaning.
multiline reflects whether multiple lines of text match, $* means the same. RegExp's properties, static
Provided in JavaScript 1.2, NES 3.0 or above

Description: Because multiline is static, not the attribute of a certain regular expression, the same meaning can be expressed.
If multiple lines of text are allowed to match, multiline is true, and false if the search must stop on a newline.
Scripts or browsers can set multiline properties. When a textarea event processing handle is called, multiline
Set to true. After the event processing handle is processed, the multiline attribute value is cleared. That is, if you set multiline to true, then after executing any event handling handles, multiline is set to false. prototype
Delineate the prototype of the class. You can use prototype to add properties or methods of the class as required. To obtain the profile of prototypes, see the properties of RegExp. It is available from JavaScript 1.1, NES 2.0
ECMA version ECMA-262 rightContext The last matched string to the right, $' is the same effect.
RegExp's properties, static, read-only provided from JavaScript 1.2, NES 3.0 or above

Description: Because rightContext is static and not a property of a certain regular expression worker, it can be used to achieve the same effect.
source A read-only property that contains the pattern defined by regular expressions, does not include forward slashes and "g" or "i" tags. RegExp's property, read only
Provided from JavaScript 1.2, NES 3.0 or above

Description: source is an attribute of an individual regular expression object. You cannot directly change its value, but you can change it by calling the compile method. test
Performs a regular expression matching search for the specified string, returning true or false. RegExp method
Provided from JavaScript 1.2, NES 3.0 or above. Syntax: ([str])

Parameters: regexp, the name of the regular expression, can be a variable name or a regular expression definition literal string
str, if omitted, the value used is used as a parameter

Description: When you need to know whether a string can match a regular expression worker, you can use the test method (with the square
The exec method can be used (similar to the method) in order to obtain more information (but will slow down). Example: The following example shows a prompt for whether the test is successful:

function testinput(re, str){
if ((str)) midstring = " contains ";
else midstring = " does not contain ";
(str + midstring + ); } toSource

Return the source code of a string symbolic object. The method of RegExp is provided from JavaScript 1.3 or above. Syntax: toSource()

Parameters: None Description: the toSource method returns the following value: For the built-in RegExp object, the source code of toSource returns the following character symbol is not available:
function Boolean(){ [native code] }
In RegExp, toSource returns a string that symbolizes the source code. Usually this method is automatically called internally by JavaScript rather than explicitly called in code.
For more, see toString Returns a string that depicts the specified object. RegExp method
Since JavaScript 1.1, NES 2.0, ECMA version ECMA-262 Syntax: toString() Parameters: None

Description: RegExp object does not consider the toString method of the Object object; it does not inherit, for RegExp
The toString method returns a string representing the object. For example: The following example shows a string that symbolizes the RegExp object
myExp = new RegExp("a+b+c"); alert(())
displays "/a+b+c/" For more information, please see: valueOf Returns the original value of a RegExp object
RegExp method provides ECMA version: ECMA-262 Syntax: valueOf()

Parameters: None Description: RegExp's valueOf method returns the original value of the RegExp object in a string, which is equal to it.
This method is usually called automatically internally by JavaScript rather than explicitly. Example: myExp = new RegExp("a+b+c");
alert(()) displays "/a+b+c/"


Several instances of regular expressions in javascript 1 (redirect)

! Processing of removing spaces at both ends of strings

If you adopt the traditional method, you will probably need to use the following method.

Copy the codeThe code is as follows:

//Clear the space on the left
function js_ltrim(deststr)
{
if(deststr==null)return "";
var pos=0;
var retStr=new String(deststr);
if (==0) return retStr;
while ((pos,pos+1)==" ") pos++;
retStr=(pos);
return(retStr);
}
//Clear the space on the right
function js_rtrim(deststr)
{
if(deststr==null)return "";
var retStr=new String(deststr);
var pos=;
if (pos==0) return retStr;
while (pos && (pos-1,pos)==" " ) pos--;
retStr=(0,pos);
return(retStr);
}
//Clear the spaces on the left and right
function js_trim(deststr)
{
if(deststr==null)return "";
var retStr=new String(deststr);
var pos=;
if (pos==0) return retStr;
retStr=js_ltrim(retStr);
retStr=js_rtrim(retStr);
return retStr;
}

Use regular expressions to remove spaces on both sides, just the following code
= function()
{
return (/(^\s*)|(\s*$)/g, "");
}

It's done in one sentence,
The visible regular expression saves us a considerable amount of code writing


! Verification of mobile phone number

If the traditional verification method is adopted, at least the following three steps must be completed.

(1). Whether it is a number

(2). Is it 11 bits?

(3). Is the third digit of the number 5, 6, 7, 8, 9?

If you use regular expression verification, just the following code is required

Copy the codeThe code is as follows:

function checkMobile1(form)
{
if ( > "")
{
var reg=/13[5,6,7,8,9]\d{8}/;
if ( (reg)== null)
{
alert("Please enter the correct mobile phone number!");
(); return false;
}
}
return true;
}

From the above code, we can see that checking the mobile phone number requires only a var reg=/13[5,6,7,8,9]\d{8}/; pattern matching string to complete the legality verification.

! URL verification,
Condition: Must start with http:// or https://, the port number must be between 1-65535, the following code completes the legality verification

Copy the codeThe code is as follows:

//obj:Data object
//dispStr: The failure prompt displays the string
function checkUrlValid( obj, dispStr)
{
if(obj == null)
{
alert("The incoming object is empty");
return false;
}
var str = ;

var urlpatern0 = /^https?:\/\/.+$/i;
if(!(str))
{
alert(dispStr+"Illegal: Must start with 'http:\/\/' or 'https:\/\/'!");
();
return false;
}

var urlpatern2= /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?.+$/i;
if(!(str))
{
alert(dispStr+"The port number must be a number and should be between 1-65535!");
();
return false;
}


var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;

if(!(str))
{
alert(dispStr+"Illegal, please check!");
();
return false;
}

var s = "0";
var t =0;
var re = new RegExp(":\\d+","ig");
while((arr = (str))!=null)
{
s = (+1,);

if((0,1)=="0")
{
alert(dispStr+"Port number cannot start with 0!");
();
return false;
}

t = parseInt(s);
if(t<1 || t >65535)
{
alert(dispStr+"The port number must be a number and should be between 1-65535!");
();
return false;
}
}
return true;
}


There seems to be a lot of code for the verification of url, because you want to give an error message, otherwise you only need var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i; You can verify the legality of url in one sentence.


Regular expressions in JavaScript application

--------------------------------------------------------------
Remove extra spaces at the beginning and end of a string
/g is to find all matches in the full text

function (){return (/(^\s*)|(\s*$)/g, "");}

function (){return (/(^\s*)/g, "");}

function (){return (/(\s*$)/g, "");}

--------------------------------------------------------------
Application: Calculate the length of the string (one double-byte character length meter 2, ASCII character meter 1)

=function(){return ([^\x00-\xff]/g,"aa").length;}

--------------------------------------------------------------
Application: There is no trim function like vbscript in JavaScript, we can use this expression to implement it, as follows:

= function()
{
return (/(^\s*)|(\s*$)/g, "");
}
You need to use regular expressions to extract file names from URL address, as shown in page1

s="https:///"
s=(/(.*\/){0,}([^\.]+).*/ig,"$2")
alert(s)

##Use regular expressions to restrict input content in text boxes in web forms:

--------------------------------------------------------------
Use regular expressions to restrict only Chinese: onkeyup="value=(/[^\u4E00-\u9FA5]/g,')" onbeforepaste="('text',('text').replace(/[^\u4E00-\u9FA5]/g,'))"

--------------------------------------------------------------
Use regular expressions to restrict only full-width characters: onkeyup="value=(/[^\uFF00-\uFFFF]/g,')" onbeforepaste="('text',('text').replace(/[^\uFF00-\uFFF]/g,'))"

--------------------------------------------------------------
Use regular expressions to limit only numeric input: onkeyup="value=(/[^\d]/g,') "onbeforepaste="('text',('text').replace(/[^\d]/g,'))"

--------------------------------------------------------------
Use regular expressions to restrict only numeric and English: onkeyup="value=(/[\W]/g,') "onbeforepaste="('text',('text').replace(/[^\d]/g,'))"
 

Use regular expressions and javascript to conduct comprehensive verification of forms

When using it, please save the following javascript code into a single js file.

1. Form requirements
<form name="formname" onSubmit="return validateForm(this)"></form>
All the following fields in the form are verified in sequence. All verifications are removed from leading and suffix spaces, and be careful to be case sensitive.

2. Null value verification
Adding the emptyInfo attribute to any field in the form will verify whether this field is empty (can be used at the same time as the maximum length verification\general verification method).
None of this property is considered to be allowed in this field.
For example: <input type="text" name="fieldNamename" emptyInfo="field cannot be empty!">

3. Maximum length verification (can be used at the same time as null value verification and general verification methods):
<input type="text" name="fieldNamename" maxlength="20" lengthInfo="maximum length cannot exceed 20!">
Or, <textarea maxlength="2000" lengthInfo="Maximum length cannot exceed 2000!">

3. General verification method (no verification of null values):
For example: <input type="text" validator="^(19|20)[0-9]{2}$" errorInfo="incorrect year!" >

4. Standard verification (not used at the same time as other verification methods):
All are implemented through <input type="hidden"> and no name attribute is required to avoid committing to the server.

4.1. Legal date verification:
<input type="text" name="yearfieldName" value="2004">Note: Here it can also be <select name="yearfieldName"></select>, the following are the same
<input type="text" name="monthfieldName" value="02">
<input type="text" name="dayfieldName" value="03">
<input type="hidden" validatorType="DateGroup" year="yearfieldName" month="monthfieldName" day="dayfieldName" errorInfo="incorrect date!">
yearfieldName, monthfieldName, and dayfieldName are respectively the year, month and day fields. The month and day can be in two digits (MM) or one-bit format (M).
Here, each field is not checked separately (if you want to check, please use the previous general verification method in the three fields of year, month and day), and only check whether the maximum value of the date is legal;

4.2. Date format verification (please note that this verification does not verify whether the date is valid. No method to obtain year, month and day data from the format^_^):
<input type="text" name="datefieldName" value="2003-01-03 21:31:00">
<input type="hidden" validatorType="Date" fieldName="datefieldName"; format="yyyy-MM-dd HH:mm:ss" errorInfo="Incorrect date!">
The format only supports y, M, d, H, m, and s (other characters are regarded as non-time characters)

4.3. List verification:
Check whether at least one record is selected on the list (checkbox, redio, select) (select is mainly used for multiple selections)
<input type="checkbox" name="checkbox1">
<input type="hidden" validatorType="Checkbox" fieldName="checkbox1" errorInfo="Please select at least one record!">
Where validatorType can be Checkbox, R, Select;
For a select form, if you ask to select a record that cannot be the first one, please use the following method:
<select name="select1" emptyInfo="Please select an option!">
<option value="">==Please select ==</option>
<option value="1">1</option>
<select>

4.4. Email verification:
<input type="text" name="email">
<input type="hidden" fieldName="email" validatorType="Email" separator="," errorInfo="incorrect email!">
Where separator is optional, indicating the separator when entering multiple emails (no this option can only be one address)

4.5. Add other javascript operations:
<script type="text/javascript">
function functionname(){
Custom Method
}
</script>
Add <input type="hidden" validatorType="javascript" functionName="functionname"> to the form (at this time emptyInfo and other properties are invalid)
The javascript method specified in the function attribute will be called (requiring the method to return true or false, return false will no longer validate the form, nor submit the form).

5. Disable a button before the form passes verification and submits (other domains can also be disabled, and cannot be in the same domain as other verifications). The button is not required to be the last one in the form.
<input type="button" name="submit" validatorType="disable">

6. No verification form
<input type="hidden" name="validate" value="0" functionName="functionname">
When the validator field value is 0, the form is not validated. Submit the form directly or execute the specified function and return true. Submit the form.
functionName is optional

Copy the codeThe code is as follows:

<script type="text/javascript">
function getStringLength(str){
var endvalue=0;
var sourcestr=new String(str);
var tempstr;
for (var strposition = 0; strposition < ; strposition ++) {
tempstr=(strposition);
if ((0)>255 || (0)<0) {
endvalue=endvalue+2;
} else {
endvalue=endvalue+1;
}
}
return(endvalue);
}
function trim(str){
if(str==null) return "";
if(==0) return "";
var i=0,j=-1,c;
for(;i<;i++){
c=(i);
if(c!=' ') break;
}
for(;j>-1;j--){
c=(j);
if(c!=' ') break;
}
if(i>j) return "";
return (i,j+1);
}
function validateDate(date,format,alt){
var time=trim();
if(time=="") return;
var reg=format;
var reg=(/yyyy/,"[0-9]{4}");
var reg=(/yy/,"[0-9]{2}");
var reg=(/MM/,"((0[1-9])|1[0-2])");
var reg=(/M/,"(([1-9])|1[0-2])");
var reg=(/dd/,"((0[1-9])|([1-2][0-9])|30|31)");
var reg=(/d/,"([1-9]|[1-2][0-9]|30|31))");
var reg=(/HH/,"(([0-1][0-9])|20|21|22|23)");
var reg=(/H/,"([0-9]|1[0-9]|20|21|22|23)");
var reg=(/mm/,"([0-5][0-9])");
var reg=(/m/,"([0-9]|([1-5][0-9]))");
var reg=(/ss/,"([0-5][0-9])");
var reg=(/s/,"([0-9]|([1-5][0-9]))");
reg=new RegExp("^"+reg+"$");
if((time)==false){//Verify whether the format is legal
alert(alt);
();
return false;
}
return true;
}
function validateDateGroup(year,month,day,alt){
var array=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var y=parseInt();
var m=parseInt();
var d=parseInt();
var maxday=array[m-1];
if(m==2){
if((y%4==0&&y%100!=0)||y%400==0){
maxday=29;
}
}
if(d>maxday){
alert(alt);
return false;
}
return true;
}
function validateCheckbox(obj,alt){
var rs=false;
if(obj!=null){
if(==null){
return ;
}
for(i=0;i<;i++){
if(obj[i].checked==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateRadio(obj,alt){
var rs=false;
if(obj!=null){
if(==null){
return ;
}
for(i=0;i<;i++){
if(obj[i].checked==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateSelect(obj,alt){
var rs=false;
if(obj!=null){
for(i=0;i<;i++){
if([i].selected==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateEmail(email,alt,separator){
var mail=trim();
if(mail=="") return;
var em;
var myReg = /^[_a-z0-9]+@([_a-z0-9]+\.)+[a-z0-9]{2,3}$/;
if(separator==null){
if(()==false){
alert(alt);
();
return false;
}
}
else{
em=(separator);
for(i=0;i<;i++){
em[i]=em[i].trim();
if(em[i].length>0&&(em[i])==false){
alert(alt);
();
return false;
}
}
}
return true;
}
function validateForm(theForm){// Return true if the verification is passed
var disableList=new Array();
var field = ; // Put all elements in the form into an array
for(var i = 0; i < ; i++){
var vali=;
if(vali!=null){
if(=="0"){
var fun=;
if(fun!=null){
return eval(fun+"()");
}
else{
return true;
}
}
}

var empty=false;
var value=trim(field[i].value);
if(==0){//Is it empty?
empty=true;
}
var emptyInfo=field[i].emptyInfo;//Null value verification
if(emptyInfo!=null&&empty==true){
alert(emptyInfo);
field[i].focus();
return false;
}
var lengthInfo=field[i].lengthInfo;//Maximum length verification
if(lengthInfo!=null&&getStringLength(value)>field[i].maxLength){
alert(lengthInfo);
field[i].focus();
return false;
}

var validatorType=field[i].validatorType;
if(validatorType!=null){//Other javascript
var rs=true;
if(validatorType=="javascript"){
eval("rs="+field[i].functionName+"()");
if(rs==false){
return false;
}
else{
continue;
}
}
else if(validatorType=="disable"){//The button that disable before submitting the form
++;
disableList[-1]=field[i];
continue;
}
else if(validatorType=="Date"){
rs=validateDate((field[i].fieldName),field[i].format,field[i].errorInfo);
}
else if(validatorType=="DateGroup"){
rs=validateDateGroup((field[i].year),(field[i].month),(field[i].day),field[i].errorInfo);
}
else if(validatorType=="Checkbox"){
rs=validateCheckbox((field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Radio"){
rs=validateRadio((field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Select"){
rs=validateSelect((field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Email"){
rs=validateEmail((field[i].fieldName),field[i].errorInfo);
}
else{
alert("The verification type is not supported, fieldName: "+field[i].name);
return false;
}
if(rs==false){
return false;
}
}
else{//General verification
if(empty==false){
var v = field[i].validator; // Get its validator property
if(!v) continue; // If the attribute does not exist, the current element is ignored
var reg=new RegExp(v);
if((field[i].value)==false){
alert(field[i].errorInfo);
field[i].focus();
return false;
}
}
}
}
for(i=0;i<;i++){
disableList[i].disabled=true;
}
return true;
}
</script>