html表单的JavaScript验证

时间:2017-04-10 18:39:22

标签: javascript php html validation

我有一个包含HTML注册表单的PHP文件。表单由几个字段组成,包括电话号码,密码和重复密码字段。

我希望验证这些字段,并需要有关如何验证用户输入的一些指导。应该需要这些字段,并且两个密码字段应该匹配。

如果验证失败,我希望用户收到反馈并阻止提交表单。

如果通过,则应提交表格。

<div id="id02" class="modal">
<form class="modal-content animate" action="register.php" method="post">    
    <div class="imgcontainer">
        <span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">&times;</span>
    </div>
    <div class="container">
        <label><b>Name:</b></label>
        <input type="text" placeholder="Enter Name" name="name" required>     
        <label><b>Phone No.:</b></label>
        <input type="text" placeholder="Enter Phone number" name="phone" required>  
        <label><b>Date of Birth:</b></label>
        <input type="date" placeholder="Enter Date of Birth" name="dob" required>
        <label><b>E-mail:</b></label>
        <input type="text" placeholder="Enter Email" name="email" required>
        <label><b>Password:</b></label>
        <input type="password" placeholder="Enter Password" name="psw" required>
        <label><b>Repeat Password:</b></label>
        <input type="password" placeholder="Repeat Password" name="psw-repeat" required>     
        <input type="checkbox" checked="checked"> Remember me
        <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
        <div class="clearfix">      
            <button type="submit" class="register">Register</button>
            <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>     
        </div>
    </div>
</form>
<script>
// Get the modal
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) 
{
    if (event.target == modal) 
    {
        modal.style.display = "none";
    }
}
</script>       

1 个答案:

答案 0 :(得分:0)

取自https://www.w3schools.com/js/js_validation.asp(谷歌搜索您的问题时的第一个谷歌搜索结果之一。您可能希望下次自己这样做。)

您可能希望像这样调整代码:

<form class="modal-content animate" action="register.php" onsubmit="return validateForm()" name="formToValidate" method="post">

[...]您的其他代码[...]

function validateForm() {

    // get value of phone number field
    var x = document.forms["formToValidate"]["phone"].value;

    // check phone number for being empty
    if (x == "") {
        alert("Phone number must be filled in");
        // return false to interupt the POST request.
        return false;
    }

    // copy, paste and adapt for the other form elements

}