Home >Web Front-end >JS Tutorial >JavaScript implements client-side validation handler through RegExp_javascript tips

JavaScript implements client-side validation handler through RegExp_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:34:261126browse
1. Let the text box only allow numbers to be entered, using the text box control of asp.net mvc3.0
Copy code The code is as follows:

@Html.TextBox("txt",null, new {@style="width:300;",onkeypress="return RegValidateIsDigit(event)" })

You can see that the onkeypress event is registered in the text box. When a character is entered in the text box and the keyboard is pressed, the JavaScript function will be triggered
Copy code The code is as follows:



First judge the browser and process it compatibility. Then use String.formCharCode(KeyChar) to find the corresponding character
Finally, in the function regIsDigit function
define the regular pattern for matching
Copy code The code is as follows:

var reg = new RegExp("^[0-9]$");

Because it is a numerical value 0-9. It is also equivalent to d, that is,
Copy code The code is as follows:

var reg = new RegExp(" \d$");

Regular expression literals are also defined as characters contained between a pair of slashes (/). Therefore, JavaScript may contain the following code:
Copy code The code is as follows:

var reg=/d$/;

The test function is also used here: Check whether the specified string exists. Commonly used functions include exec match search replace split and other functions.
If you understand the first one, you only need to apply the regular expression and you can use it.
2. The text box only allows Chinese input
Copy code The code is as follows:

function RegValidateIsChinese(str) {
//var reg = new RegExp("^[u4e00-u9fa5] $");
var reg = /^[u4E00-u9FA5] $/;
var str=document.getElementById("text").value;
return (reg.test(str));
}

RegValidateIsChinese("Input string" ) is a Chinese character, it returns true, if it is not all Chinese characters, it returns false
3. Judgment of email input format
Copy code The code is as follows:

function RegValidateIsEmail(str) {
//var reg = /^([a-zA-Z0-9_-]) @@([a -zA-Z0-9_-]) ((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
var reg=/^w ((-w )|(.w ))*@@{1}w .{1}w{2,4}(.{0,1}w{2}){0,1}/ig;
if (reg .test(str)) {
alert("It's an email address");
}
else {
alert("Incorrect format");
}
}

Both definitions are acceptable for preliminary testing.
Statement:
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