This article mainly introduces the sample code for js special character filtering. For more information, see.
The Code is as follows:
// Match Chinese characters, numbers, and underscores
Var checkInput = function (str ){
Var pattern =/^ [\ w \ u4e00-\ u9fa5] + $/gi;
If (pattern. test (c ))
{
Return false;
}
Return true;
}
1. Use Regular Expressions in js to filter out special characters and check whether all input fields contain special characters.
The Code is as follows:
Function stripscript (s ){
Var pattern = new RegExp ("['~! @ # $ ^ & * () = | {} ':;', \ [\]. <> /?~! @ # ¥ ...... & * () -- | {} [] ';: "'., ,?] ")
Var rs = "";
For (var I = 0; I <s. length; I ++ ){
Rs = rs + s. substr (I, 1). replace (pattern ,'');
}
Return rs;
}
2. Verify that all input fields contain special characters
The Code is as follows:
/**
* Check whether all input fields contain special characters
* The symbol to be filtered is written into the regular expression. Note that some symbols must be escaped using.
* Example:
* If (checkAllTextValid (document. forms [0])
* Alert ("all text boxes in the form are verified! ");
*/
Function checkAllTextValid (form ){
// Record the number of text boxes without quotation marks
Var resultTag = 0;
// Record the number of all text boxes
Var flag = 0;
For (var I = 0; I <form. elements. length; I ++ ){
If (form. elements [I]. type = "text "){
Flag = flag + 1;
// Enter the special characters to be filtered.
// Note: Modify the #### character. do not modify the other part.
// If (/^ [^ ####] * $/. test (form. elements [I]. value ))
If (/^ [^ \ | "'<>] * $/. test (form. elements [I]. value ))
ResultTag = resultTag + 1;
Else
Form. elements [I]. select ();
}
}
/**
* If the enclosed text box is equal to the value of all text boxes, the verification is successful.
*/
If (resultTag = flag)
Return true;
Else {
Alert ("the text box cannot contain \ n 1 single quotation marks: '\ n 2 double quotation marks: \" \ n 3 vertical bars: | \ n 4 tip number: <> \ n check the input! ");
Return false;
}
}