How to use JavaScript and regular expressions for data validation

Source: Internet
Author: User

With the advantage of client-side JavaScript, regular expressions in JavaScript can simplify the work of data validation, and below share with you how to use JavaScript and regular expressions for data validation, interested friends can refer to the next ha

Data validation is an important step for Web applications to receive data from clients, after all, you need to make sure that it meets the expected format before you use customer data. In a Web application, you can choose tools that use specific platforms, such as ASP. NET, JSP, and so on, or you can take advantage of client-side JavaScript, where regular expressions in JavaScript can simplify the work of data validation.

Regular Expressions
Regular expressions are a pattern-matching tool that allows you to express patterns in a literal way, so regular expressions become a powerful tool for validating textual data. In addition to pattern matching, regular expressions can also be used for text substitution. The support for regular expressions has been extending since I first approached the regular expression when I was using Perl on a UNIX system.
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 master, let's look at some of the basics of using regular expressions.

Basic Syntax
The syntax of regular expressions can be very complex to apply, and even require an entire book to explain the topic, but I'll explain some of the basics to help you get a preliminary understanding of regular expressions.
A basic concept is the anchor (anchor), which allows you to specify the starting and ending points of a string, and the caret (^) to specify the starting point of the string and the dollar sign ($) to indicate the endpoint. If you need to include a caret or dollar sign in the query string, you can do so with an escape sequence that 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 find a set of characters, as long as they are placed in square brackets, such as [and], matching characters must belong to this group of characters, an example is in the range of [12345] to find the matching number 1 to 5, the regular expression can also be written [1-5].
Many times you may need to specify a character that can appear more than once, or an optional character, a question mark (?). 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 take a look at how to apply these simple regular expressions to JavaScript.

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

Using Strings
Each JavaScript string can support regular expressions in three ways, three of which 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 (): Used for regular expression matching, if multiple matches appear, returns an array with all matching results, each entry in the array is a copy containing the matching data, or null if there are no matching values.

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

Search (): For searching for a matching value between a regular expression and a specified string, returns the index value of the string if there is a matching value, 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 a pattern of regular expressions that can be used to match strings, and there are two ways to create an instance of a RegExp object: Using a constructor or using a regular expression literal pattern, the second argument is optional, and the parameter can specify that the search is global (g), ignoring case (i), or global ignoring case (GI). The following example is a method of creating a RegExp object using a constructor, in which case the search object is ignored in the following code:


New


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

The code is as follows:


The RegExp object contains a number of methods, but we only introduce one of the methods test. The method will match the specified string with a regular expression, and if successful returns TRUE, the failure returns false, the method can be applied to a literal string or a string variable, which basically allows you to match a regular expression to a string, and the following example demonstrates how to use this method:

The code is as follows:
testregexp =/search/i; if (Testregexp.test ("A search string") {document.write ("the string was found.");} El SE {document.write ("No match found.");} We can place it on a Web page to test:<HTML><Head> <title>REGEXP Test</title> </Head><Body> <Scriptlanguage= "JavaScript">Testregexp= /Search/i;if(Testregexp.test ("This is a search string") {alert ("The string was found."); } Else{alert ("No match found."); } </Script></Body></HTML> 

actual Operation
Now is the time to explain a more complete example, the page in List A contains the JavaScript method to verify the value entered in the text box, this JavaScript code will search for the string containing my last name and my two names (ignoring case), if I find my name, Replace it with a short name by using the Replace method (search) of the string object. The second text box is used to accept the time value, and a regular expression validates the time of the input (the number is separated by a colon). This simple example shows how to include a regular expression in your client code to match and replace:

1 <HTML>2 <Head> 3 <title>REGEXP validation</title> 4 <Scriptlanguage= "JavaScript"> 5 functionValidate () {6 varDoc=document.test;7 var valName= NewRegExp ("^ (tony| Anthony) Patton", "I"); 8 if(Doc. Name.value.match (ValName)== NULL) { 9 Alert ("Name is not found."); Ten } Else {  One Doc. Name.value=Doc. Name.value.replace (ValName,"T. Patton");  A }  - var valtime= NewRegExp ("^ ([0-1][0-9]|[ 2][0-3]):([0-5][0-9]) $");  - if(Doc.time.value.match (valtime)== NULL) {  the Alert ("Please enter correct time format (HH:SS)");  - } }  - </Script> - </Head>  + <Body> - <formname= "Test">  +Name:<inputtype= "text"name= "Name"value=""><BR>  ATime:<inputtype= "text"name= "Time"value=""><BR>  at <inputtype= "button"name= "Test"value= "Test"OnClick= "Validate ();">  - </form> - </Body> - </HTML> 

Powerful and complex
Regular expressions are really powerful, but they're not easy to use, so you should learn incrementally, and of course it's worth your time to learn how to use them correctly. Regular expressions for JavaScript (and other languages) manipulate text, and universal software provides a simple and elegant way to validate forms.

How to use JavaScript and regular expressions for data validation

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.