亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 JavaScript 中確認兩個密碼相等

如何在 JavaScript 中確認兩個密碼相等

RISEBY 2021-12-23 17:01:25
我正在嘗試在 JS 中制作一個簡單的密碼確認器?;旧嫌脩粲?2 個輸入字段,如果它們匹配,則不會發生任何事情,但如果它們不匹配,則會出現一個警報窗口這也是我第一天使用 javascript,也是我關于 Stack Overflow 的第一個問題,對于任何錯誤或不幸,我深表歉意。謝謝<body>    <form>        Password:<br>        <input type="password" name="password" placeholder="Password">        <br>        Re-enter Password:<br>        <input type="password" name="confirmPassword" placeholder="Confirm password">        <br>        <input type="submit" onclick="ansValidation()" value="Sign Up">    </form>    <br>    <script>        function ansValidation() {            var nameValue = document.getElementById("name")            var passValue = document.getElementById("password")            var confpassValue = document.getElementById("confirmPassword")            if(typeof nameValue != String){                window.alert("Please re-enter your name")            }else if(passValue != confpassValue) {               window.alert("Passwords do not match!")            }        }    </script></body>
查看完整描述

1 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

該document.getElementById函數返回一個節點,而不是來自輸入的值。您需要調用value這些節點上的屬性來訪問它們的值。


function ansValidation(ev) {

    ev.preventDefault

    // there is no input named name

    //var nameValue = document.getElementById("name").value

    var nameValue = "test";

    var passValue = document.getElementById("password").value

    var confpassValue = document.getElementById("confirmPassword").value

    // the typeof operator returns a string.

    if(typeof nameValue !== "string"){

        window.alert("Please re-enter your name")

    // we use strict validation ( !== ) because it's a good practice.

    }else if(passValue !== confpassValue) {

       window.alert("Passwords do not match!")

    }

}

<form>

    Password:<br>

    <input type="password" id="password" placeholder="Password">

    <br>

    Re-enter Password:<br>

    <input type="password" id="confirmPassword" placeholder="Confirm password">

    <br>

    <input type="button" href="#" onclick="ansValidation(event)" value="Sign Up">

</form>

 

我還編輯了您的代碼以使其在代碼段中工作。這是它遇到的一些問題。


  • id=""如果要使用該getElementById函數,則需要將屬性傳遞給輸入

  • 輸入name不存在

  • 運算符typeof返回一個字符串,您需要將其與字符串進行比較。

  • 在 Javascript 中比較事物時,嚴格比較事物 ( ===)始終是一個好習慣。

  • 我已將事件添加到函數中,ev.preventDefault以確保在發送表單之前正確完成驗證。


查看完整回答
反對 回復 2021-12-23
  • 1 回答
  • 0 關注
  • 285 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號