Home > Web Front-end > JS Tutorial > How to use JavaScript and regular expressions for data validation

How to use JavaScript and regular expressions for data validation

高洛峰
Release: 2017-01-14 09:55:04
Original
1144 people have browsed it

Data validation is an important step for web applications to accept data from clients. After all, you need to ensure that customer data conforms to the expected format before using it. In web applications, you can choose to use platform-specific tools such as ASP.NET, JSP, etc., or you can take advantage of client-side JavaScript. Regular expressions in JavaScript can simplify the work of data validation.

Regular expression
Regular expression is a pattern matching tool that allows you to express patterns in text, so regular expressions become a powerful tool for validating text data. In addition to pattern matching, regular expressions can also be used for text replacement. Support for regular expressions has continued to expand since I first encountered them while using Perl on a UNIX system.
Note: If there are many other developers around you, the regular expression may be called RegEx or RegExp. Although regular expressions are powerful, their syntax is a bit "mysterious" and takes some time to master. Let's take a look at some basic knowledge of using regular expressions.

Basic Grammar
The syntax of regular expressions can be very complicated to apply, and it would even take a whole book to explain this topic, but I will explain some of the basic knowledge to help you get a preliminary understanding of regular expressions. know.
A basic concept is the anchor, which allows you to specify the starting and ending points of a string. The caret (^) is used to specify the starting point of the string and the dollar sign ($) indicates the ending point. If you need to include a caret or dollar sign in the query string, you can use an escape sequence. The escape character () takes precedence over the caret or dollar sign. The following example will match the word search whenever it occurs in a string.

^search$
Moreover, you can also search for a group of characters, just put them in square brackets, such as [and], the matching characters must belong to this character group, an example It is to find matching numbers 1 to 5 in the range of [12345]. This regular expression can also be written as [1-5].
Many times you may need to specify a character that can appear multiple times, or an optional character. The question mark (?) means that the character is optional, and the plus sign (+) means that the character can appear once or Multiple times, the asterisk (*) means that the character may not appear or appear multiple times.
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 with Internet Explorer 4 and Netscape 4, all Firefox versions and most modern browsers Includes JavaScript support. Regular expressions can be used through JavaScript strings and RegExp.

Using strings
Every JavaScript string can support regular expressions through three methods, these three methods are match(), replace() and search(), and the test of the object The () method also allows you to do testing. The following is information about the match(), replace() and search() methods:
match(): used for regular expression matching. If multiple matches occur, an array containing all matching results is returned. Each entry in is a copy containing matching data; if there is no matching value, a null value is returned.

replace(): Used for regular expression matching and replacing all matching values ​​​​with new substrings. The first parameter of this method is the regular expression, and the second parameter is used for replacement. string.

search(): Used to search for a matching value between a regular expression and a specified string. If a matching value occurs, the index value of the string is returned. If there is no matching value, -1 is returned.

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

RegExp
The RegExp object contains a regular expression pattern. The methods and properties of this object can be used to match strings. There are two ways to create an instance of a RegExp object: using the constructor or Using the literal mode of regular expression text mode, the second parameter is optional, which can specify whether the search is global (g), case-insensitive (i), or both global and case-insensitive (gi). The following example uses the constructor to create a RegExp object. In this example, the case of the search object is ignored:

testRegExp = new RegExp("^search$","I")
Copy after login

You can create the same instance using the literal method (in slashes part), as shown below:

testRegExp = /^search$/i
Copy after login

RegExp object contains a large number of methods, but we only introduce one of them, test. This method will perform a regular expression match on the specified string, returning true if successful and false on failure. This method can be applied to literal strings or string variables. Basically, it allows you to regularize a string. Expression matching, the following example demonstrates how to use this method:

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: 
<html><head> 
<title>RegExp test</title> 
</head><body> 
<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></html>
Copy after login

实际操作
现在是讲解更加完整的例子的时候了,在列表A中的网页包含了JavaScript方法来验证文本框中输入的值,这段JavaScript代码将搜索包含我的姓氏和我的两个名字的字符串(忽略大小写),如果找到了我的名字,则通过字符串对象的替换方法(search)将其替换为一个短名字。第二个文本框是用于接受时间值的,一个正则表达式在此对输入的时间进行合法性验证(数字是通过冒号分割的)。这个简单的例子说明了如何在您的客户端代码中加入正则表达式来进行匹配和替换:

<html><head> 
<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 was 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></head> 
<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></html>
Copy after login

强大而复杂 
正则表达式的功能确实很强大,但是使用起来也并不简单,因此,应当循序渐进地学习,当然,它确实值得您花上一些时间来学习如何正确使用。正则表达式为JavaScript (以及其他的语言)操作文本,通用软件进行表单验证提供了一个简单而优雅的方法。

更多如何使用JavaScript和正则表达式进行数据验证相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template