How to use JavaScript and regular expressions for data validation _ regular expressions

Source: Internet
Author: User
Data validation is an important step for network applications to accept data from the client, after all, you need to ensure that they conform to the expected format before using customer data. In Web applications, you can choose to use specific platform tools such as ASP.net, JSPs, and so on, or you can take advantage of client JavaScript, which can simplify data validation by using regular expressions in JavaScript.

Regular Expressions
A regular expression is a pattern-matching tool that allows you to express patterns in a literal way, so regular expressions become a powerful tool for validating text data. In addition to pattern matching, regular expressions can also be used for text substitution. The support for regular expressions has been extended since I first came into contact with regular expressions when I used Perl on UNIX systems.
Note: If you have many other developers around you, regular expressions may be called regex or regexp. Although the regular expression is powerful, but its syntax is a bit "mysterious" and takes some time to grasp, let's take a look at some of the basics of using regular expressions.

Basic Syntax
The syntax of regular expressions can be complex to use, and even a whole book is needed to explain the topic, but I'll explain some of the basics to help you get a rudimentary understanding of regular expressions.
A basic concept is anchor, which allows you to specify the beginning and end of a string, and the caret (^) to specify the starting point of the string, and the dollar sign ($) to indicate the end point. If you need to include a caret or dollar sign in the query string, you can use the escape sequence to implement the escape character (), which takes precedence over the caret or dollar sign. The following example matches the word search when it appears in a string.

^search$
Also, you can look up a set of characters, just put them in square brackets, such as [and], matching characters must belong to this character group, an example is in [12345] to find a matching number 1 to 5, the regular expression can also write [1-5].
Many times you may want to specify a character that can appear multiple times, or an optional character, a question mark (?). It means that the character is optional, and the plus sign (+) means that the character can appear one or more times, and the asterisk (*) means that the character may not appear or appear more than once.
Now let's look at how to apply these simple regular expressions to JavaScript.

JavaScript Support
JavaScript added support for regular expressions in version 1.2, and browser support began with Internet Explorer 4 and Netscape 4, and all Firefox versions and most modern browsers included JavaScript support. Regular expressions can be used through JavaScript strings and RegExp.

Using Strings
Each JavaScript string can support regular expressions in three ways, the three methods are match (), replace (), and search (), and the object's test () method allows you to test. The following is information about the match (), replace (), and Search () methods:
Match (): For regular expression matching, if multiple matches appear, returns an array containing all the matching results, each of which contains a copy of the matching data, or null if there is no matching value.

Replace (): Used for regular expression matching and replace all matching values with new substrings, the first parameter of this method is a regular expression and the second is a string to be substituted.

Search (): For matching values between regular expressions and specified strings, returns the index value of the string if there is a match, or 1 if there is no matching value.

JavaScript also provides a RegExp object to create and use regular expressions.

RegExp
The RegExp object contains the pattern of the regular expression. The methods and properties of this object can be used to match strings, and there are two ways to create an instance of a RegExp object: Using a constructor or a literal way of using regular expression text patterns, the second parameter is optional, which specifies that the search is global (g), ignoring case (i) or globally ignoring both case (GI). The following example is a method of creating a RegExp object using a constructor, in which case the case of the search object is ignored:
Copy Code code as follows:

Testregexp = new RegExp ("^search$", "I")

You can use text to create the same instance (part of the slash), as follows:
Copy Code code as follows:

Testregexp =/^search$/i

The RegExp object contains a number of methods, but we'll just cover one of the methods test. The method will match the specified string with a regular expression. Returns True if successful, and returns false for failure, which can be applied to literal strings or string variables, basically allowing you to match a regular expression of a string, and the following example demonstrates how to use this method:
Copy Code code as follows:

Testregexp =/search/i;
if (Testregexp.test ("This is a search string") {
document.write ("The string was found.");
} else {
document.write ("No match found.");
}
We can place it in a Web page to test:
<title>regexp test</title>
<script language= "JavaScript" >
Testregexp =/search/i;
if (Testregexp.test ("This is a search string")) {
Alert ("The string was found.");
} else {
Alert ("No match found.");
}
</script></body>

actual Operation
Now is the time to explain a more complete example, the page in List A contains a JavaScript method to validate the value entered in the text box, which searches for a string containing my last name and my two names (ignoring case), if I find my name, Replaces it with a short name through the substitution method (search) for the string object. The second text box is used to accept the time value, and a regular expression verifies the validity of the input time (the number is separated by a colon). This simple example shows how to add a regular expression to your client code to match and replace:
Copy Code code as follows:

<title>regexp validation</title>
<script language= "JavaScript" >
function Validate () {
var doc = document.test;
Varvalname = new RegExp ("^" (tony| Anthony) Patton "," I ");
if (Doc. Name.value.match (valName) = = null) {
Alert ("Name is not found.");
} else {
Doc. Name.value = doc. Name.value.replace (ValName, "T. Patton");
}
Varvaltime = new RegExp ("^" ([0-1][0-9]|[ 2][0-3]):([0-5][0-9]) $ ");
if (Doc.time.value.match (valtime) = = null) {
Alert ("Please enter correct time format (HH:SS)");
} }
</script><body><form name= "Test" >
Name: <input type= "text" name= "name" value= "" ><br>
Time: <input type= "text" name= "Time" value= "" ><br>
<input type= "button" name= "Test" value= "test" onclick= "validate ();" >
</form></body>

Powerful and complex
Regular expressions are really powerful, but they're not easy to use, so you should learn step-by-step, of course, and it's worth taking some time to learn how to use them correctly. Regular expressions manipulate text for JavaScript (and other languages), and common software provides a simple and elegant way to form validation.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.