Home  >  Article  >  Web Front-end  >  JavaScript notes forms and regular expressions

JavaScript notes forms and regular expressions

高洛峰
高洛峰Original
2016-11-26 09:57:171208browse

Regular expressions are an extremely powerful way to validate and format text strings. By using regular expressions, complex tasks that would otherwise require dozens of lines of code can be completed with one or two lines of JavaScript code.
   A regular expression is a pattern written in special symbols that describes one or more strings of text. It is often considered one of the trickiest parts of programming, but just break the mess of regular expressions into small, meaningful chunks. , its syntax is not difficult to understand.
                                                                                                                                                             The following can be used to verify email addresses using regular expressions:
[html]


;title>Email Validation



Email Validation



                                                                                                                                                        


                                                                                      

script01.css
[css]
body {

color: #000;

background-color: #FFF;
}

input.invalid {
background-color: #FF9;
border: 2px red inset;
}

label.invalid {
color: #F00;
font-weight: bold;
}

script01.js
[javascript]
window.onload = initForms; 
 
function initForms() { 
    for (var i=0; i< document.forms.length; i++) { 
        document.forms[i].onsubmit = function() {return validForm();} 
    } 

 
function validForm() { 
    var allGood = true; 
    var allTags = document.getElementsByTagName("*"); 
 
    for (var i=0; i        if (!validTag(allTags[i])) { 
            allGood = false; 
        } 
    } 
    return allGood; 
 
    function validTag(thisTag) { 
        var outClass = ""; 
        var allClasses = thisTag.className.split(" "); 
     
        for (var j=0; j            outClass += validBasedOnClass(allClasses[j]) + " "; 
        } 
     
        thisTag.className = outClass; 
     
        if (outClass.indexOf("invalid") > -1) { 
            invalidLabel(thisTag.parentNode); 
            thisTag.focus(); 
            if (thisTag.nodeName == "INPUT") { 
                thisTag.select(); 
            } 
            return false; 
        } 
        return true; 
         
        function validBasedOnClass(thisClass) { 
            var classBack = ""; 
         
            switch(thisClass) { 
                case "": 
                case "invalid": 
                    break; 
                case "email": 
                    if (allGood && !validEmail(thisTag.value)) classBack = "invalid "; 
                default: 
                    classBack += thisClass; 
            } 
            return classBack; 
        } 
                 
        function validEmail(email) { 
            var re = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/; 
 
           return re.test(email); 
        } 
         
        function invalidLabel(parentTag) { 
            if (parentTag.nodeName == "LABEL") { 
                parentTag.className += " invalid"; 
            } 
        } 
    } 

Now let’s explain the red line of code:
Regular expressions always start and end with a slash (/).
The caret (^) indicates that you want to use this expression to check for strings that start with a specific string.
The expression w represents any single character, including a~z, A~Z, 0~9 or underscore.
The plus sign + means to look for one or more occurrences of the previous entry.表示Profot parentheses (indicate a group.
square bracket [] is used to indicate any character that can appear. This square bracket contains characters .-, but the dot number has a special significance for the regular expression, so it needs to be in it in it Preceded by a backslash, this indicates that the dot is actually referring to it, rather than its special meaning. Using a backslash in front of a special string is called "character escaping"
Question mark? indicates the preceding entry. It may not appear or appear once. Use w+ again after the question mark to indicate that there must be some other characters after the period or hyphen. The parenthesis after
indicates the end of the group, indicating that the previous entry does not need to be included. Appears or appears multiple times. The @ character only represents itself and has no other meaning.
Next, w+ is used to indicate that the domain name must start with one or more a~z, A~Z, 0~9 or an underscore. This is also followed by ([.-]?w+)*, which means that dots or hyphens are allowed in the suffix of the email address. Then, create another group within a pair of parentheses: .w{2,3}. , indicating that you want to find a period, followed by some characters. The number in the curly brackets indicates that the previous entry can appear 2 or 3 times.
The end of the regular expression is a dollar sign, indicating that the matching string must be in. End here.

  Return re.test(email); This line gets the regular expression defined in the previous step and uses the test() method to verify the validity of the email
 If you don’t use a regular expression, use extra. Dozens of lines of code to complete the same code
[javascript]
function validEmail(email) {
      var invalidChars = " /:,;";
                                       
                                                                                   for (var k=0; k           var badChar = invalidChars.charAt(k);
                                                                           ;
                                                        
            var atPos = email.indexOf("@",1); 
                                                                                                                                                                    indexOf("@",atPos+1) != -1 ) {
                       return false;                                                                                                                                         return false; ) {
                           return false;                          return true;                                                                                                                     Expressions can really reduce a lot of code.



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