1. Let the text box only allow numbers to be entered, using the text box control of asp.net mvc3.0
@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
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
var reg = new RegExp("^[0-9]$");
Because it is a numerical value 0-9. It is also equivalent to d, that is,
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:
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
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
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.