使用javascript在XML中验证电子邮件是否匹配

Validate email for match in XML using javascript

本文关键字:电子邮件 是否 验证 javascript XML 使用      更新时间:2023-09-26

纠结于此,我是一名学生,请帮助我指出正确的方向。

我用下面的javascript代码检查XML文档是否有匹配的电子邮件,提醒用户并返回false。

function validateEmail() 
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() 
     {
         if (xhttp.readyState == 4 && xhttp.status == 200) 
         {
           checkEmail(xhttp);
         }
     }
     xhttp.open("GET", "customer.xml", true);
     xhttp.send();
     function checkEmail(xml) 
     {
         var xmlDoc = xml.responseXML;
         x = xmlDoc.getElementsByTagName("email");
         txt = "";
        for (i = 0; i < x.length; i++) 
        { 
           txt += x[i].childNodes[0].nodeValue;
        }
        if (document.myForm.email.value == txt ) 
           {
              alert('That email is taken');
              document.myForm.phone.focus();
              return false;
           }
        document.getElementById("test").innerHTML = txt;
     }
}

我可以得到推荐吗?它在XML文件中输出电子邮件,所以这是工作的,但if语句似乎不太正确。??

XML:

<?xml version="1.0"?>
<customers>
 <customer>
    <customerid>
        1
    </customerid>
    <firstname>
        ben
    </firstname>
    <surname>
        ben
    </surname>
    <email>
        ben@gmail.com
    </email>
    <password>
        ben
    </password>
    <phone>
    </phone>
</customer>
</customers>
HTML:

<h1>Registration</h1>
<p>New Users please enter your details below:</p>
<div id="test">TEST</div>
<fieldset>
        <form name="myForm" onsubmit="return validateForm()" method="post" >
            <legend>
                Email: <input type='email' name='email' onblur="if(this.value == '') { this.value='Your email'}" onfocus="{validateEmail()} if (this.value == 'Your email') {this.value=''}"/>
                <br><br>
                First Name: <input type='text' name='firstname'/>
                <br><br>
                Last Name: <input type='text' name='lastname'/>
                <br><br>
                Password: <input type='password' name='password'/>
                <br><br>
                Re-Type Password: <input type='password' name='password1'/> 
                <br><br>
                Phone Number:<input type='tel' name='phone'/>
                <span>* Optional </span>
                <br><br>
                <input type='Submit' value='Register' />
                <input type='Reset' value='Reset'/>
            </legend>
        </form>
</fieldset>
<br><br>
<a href='home.htm'>Home</a></p>

您正在将现有的电子邮件地址连接到字符串txt

您应该使用数组来跟踪电子邮件地址,并检查输入值是否在数组中。

function checkEmail(xml) {
    var x = xml.responseXML.getElementsByTagName("email"),
         arr = [];
    for (var i = 0; i < x.length; i++) { 
       arr.push(x[i].childNodes[0].nodeValue);
    }
    if (arr.indexOf(document.myForm.email.value) > -1) {
        alert('That email is taken');
        document.myForm.phone.focus();
        return false;
    }
 }