如何使用JavaScript重写表单验证



如何编写一个函数,当用户单击后退按钮时覆盖表单验证?

如果用户没有填写表单并点击提交,它会告诉显示"请填写此栏然后我添加了一个后退按钮以防用户不想填写表单而想要返回但点击后显示"请填写此字段">

当用户点击返回时,我如何重写这个?

function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
function goBack() {
window.history.back()
}
<div class="form-div">
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post" required>
<button onclick="goBack()">Go Back</button>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="name"><b>FullName</b></label>
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" name="fullName" id="name" required>
<label for="email"><b>Email</b></label>
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email" name="email" id="email" required>
<label for="psw"><b>Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Password" id="psw" name="psw" pattern="(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</div>

我觉得去掉' required ';属性从你的表单标签应该是好的,即使你保留这个"required"属性。

这是因为你在<form>中添加了一个按钮,导致它作为一个提交按钮
看这个:如何防止按钮提交表单

所以基本上你可以返回false,但是移除<form>

外面的按钮要容易得多供参考
总是检查输入的值,因为熟悉devTools的每个人都可以删除required属性,然后将空值发送到服务器

另一个供参考
你必须在服务器端检查这些值,因为有很多方法可以覆盖客户端检查(你做客户端检查只是为了UX)

最新更新