英文:
Form submits instead of displaying error when button is clicked
问题
我已经创建了一个名为index.html的表单。我使用JavaScript进行表单验证。当单击提交按钮时,它必须打开另一个HTML页面(detail.html)。当我提供错误的数据时,它必须阻止打开detail.html页面并显示错误消息,但这两者都没有发生。
以下是代码部分:
<form action="/detail" method="POST" role="form" name="index" onsubmit="return validateForm()" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required/>
<span class="formerror"></span>
<br />
<label for="phone_number">Mobile:</label>
<input type="number" name="phone_number" placeholder="enter your mobile number" required >
<span class="formerror"></span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="enter your password" required />
<span class="formerror"></span>
<br />
<button id="btnsubmit" class="btn" onclick="submit">Submit</button>
</form>
表单验证的代码如下:
<script>
function clearErrors(){
errors=document.getElementsByClassName('formerror');
for(let item of errors){
item.innerHTML="";
}
}
function seterror(id,error){
//设置id标签内的错误消息
element=document.getElementById(id);
element.getElementsByClassName('formerror')[0].innerHTML=error;
}
function validateForm(){
var returnval = true;
//执行验证,如果验证失败,则将returnval的值设置为false。
var name = document.forms['index']["name"].value;
if(name.length<3)
{
seterror("name","姓名太短");
returnval=false;
}
var phone_number = document.forms['index']["phone_number"].value;
if(phone_number.length!=10)
{
seterror("phone_number","手机号码应为10位数字");
returnval=false;
}
var password = document.forms['index']["password"].value;
if(password.length<4)
{
seterror("password","密码至少应为4个字符");
returnval=false;
}
return returnval;
}
</script>
我希望index.html在向输入字段提供错误数据时显示错误消息,但实际上没有发生,反而打开了detail.html页面。只有在输入正确的数据时,detail.html才应该打开。
英文:
I have made a form as index.html. I have a from validation using JavaScript. When the submit button is clicked it must open another html page(detail.html). When I supply wrong data, it must prevent the opening of detail.html page and display the error messages but neither of them happens .[](https://i.stack.imgur.com/16nTp.png)
here is the code
<form action="/detail" method="POST" role="form" name="index" onsubmit="return validateForm()" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required/>
<span class="formerror"></span>
<br />
<label for="phone_number">Mobile:</label>
<input type="number" name="phone_number" placeholder="enter your mobile number" required >
<span class="formerror"></span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="enter your password" required />
<span class="formerror"></span>
<br />
<button id="btnsubmit" class="btn" onclick="submit">Submit</button>
code for form validation
<script>
function clearErrors(){
errors=document.getElementsByClassname('formerror');
for(let item of errors){
item.innerHTML="";
}
}
function seterror(id,error){
//sets error inside tag of id
element=document.getElementById(id);
element.getElementsByClassName('formerror')[0].innerHTML=error;
}
function validateForm(){
var returnval = true;
//performs validation and if validation fails, set the value of returnval to false.
var name = document.forms['index']["name"].value;
if(name.length<3)
{
seterror("name","length of name of too short");
returnval=false;
}
var phone_number = document.forms['index']["phone_number"].value;
if(phone_number.length!=10)
{
seterror("phone_number","phone number should be of 10 digits");
returnval=false;
}
var password = document.forms['index']["password"].value;
if(password.length<4)
{
seterror("password","password should be at least of 4 characters");
returnval=false;
}
return returnval;
}
</script>
I wanted the index.html to display the error messages when wrong data is fed to the input fields, but nothing of those happens instead detail.html page opens. detail.html must only open when correct input is given.
答案1
得分: 1
以下是您要翻译的内容:
"You can make your code easier to overview if you get rid of the validate function and use event listeners instead.
The invalid
event listener will fire when the form is submitted and one or more input elements are not validating. I added attributes on each input element to validate against (like minlength="3"
for the name and pattern="[0-9]{10}"
for the telephone number). If an input element is not valid I set the invalid
className. And that results in the form error text to show.
When starting to type in an input the input event is fired, and the className is removed again."
英文:
You can make your code easier to overview if you get rid of the validate function and use event listeners instead.
The invalid
event listener will fire when the form is submitted and one or more input elements are not validating. I added attributes on each input element to validate against (like minlength="3"
for the name and pattern="[0-9]{10}"
for the telephone number). If an input element is not valid I set the invalid
className. And that results in the form error text to show.
When starting to type in an input the input event is fired, and the className is removed again.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// this first event listener is only for testing
// remove it to continue the POST request to /detail
document.forms.index.addEventListener('submit', e => {
e.preventDefault();
console.log('Submitting the form!');
});
document.forms.index.addEventListener('invalid', e => {
e.preventDefault();
e.target.classList.add('invalid');
}, true);
document.forms.index.addEventListener('input', e => {
e.preventDefault();
e.target.classList.remove('invalid');
});
<!-- language: lang-css -->
span.formerror {
display: none;
}
input.invalid ~ span.formerror {
display: inline;
}
<!-- language: lang-html -->
<form action="/detail" method="POST" role="form" name="index" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" minlength="3" placeholder="Enter your name" required>
<span class="formerror">length of name of too short</span>
<br />
<label for="phone_number">Mobile:</label>
<input type="tel" name="phone_number" pattern="[0-9]{10}" placeholder="enter your mobile number" required>
<span class="formerror">phone number should be of 10 digits</span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" minlength="3" placeholder="enter your password" required >
<span class="formerror">password should be at least of 4 characters</span>
<br />
<button class="btn">Submit</button>
</form>
<!-- end snippet -->
答案2
得分: 1
I changed your validation to use a sibling error message selected by a class selector, added some classes and CSS for that. Not perfect but shows how. Here I used the change event to clear the error.
Note I also added some validation attributes like minlength
etc.
function getNextSibling(elem, selector) {
//next sibling element
let sibling = elem.nextElementSibling;
//No selector, return the first sibling
if (!selector) return sibling;
// Sibling matches selector, use it; no? next sibling and continue loop
while (sibling) {
if (sibling.matches(selector)) {
return sibling;
}
sibling = sibling.nextElementSibling;
}
};
function clearErrors() {
let errors = document.getElementsByClassname('formerror');
for (let item of errors) {
item.textContent = "";
}
}
function seterror(element, error) {
let errSib = getNextSibling(element, '.formerror');
errSib.textContent = error;
}
function validateForm(event) {
event.preventDefault();
let returnval = true;
//performs validation and if validation fails, set the value of returnval to false.
let field = document.forms['index']["name"];
let name = field.value;
if (name.length < 3) {
seterror(field, "Length of name of too short");
returnval = false;
} else {
seterror(field, "");
}
field = document.forms['index']["phone_number"];
let phone_number = field.value;
if (phone_number.length != 10) {
seterror(field, "Phone number should be of 10 digits");
returnval = false;
} else {
seterror(field, "");
}
field = document.forms['index']["password"];
let password = document.forms['index']["password"].value;
if (password.length < 4) {
seterror(field, "Password should be at least of 4 characters");
returnval = false;
} else {
seterror(field, "");
}
return returnval;
}
document.forms.index.addEventListener('submit', e => {
e.preventDefault();
const isValid = validateForm(e);
console.log('Submitting the form!', isValid);
//note how this only fires when you have all validation pass
// check here for an entirely valid form and then submit
// left this as something yet to be done. (check for any non-value fields; several ways to do this.
});
document.forms.index.addEventListener('invalid', e => {
e.preventDefault();
e.target.classList.add('invalid');
validateForm(e);
}, true);
document.forms.index.addEventListener('change', e => {
e.preventDefault();
e.target.classList.remove('invalid');
validateForm(e);
});
form {
line-height: 2em;
}
.invalid {
border: solid red 1px;
}
.formerror {
border: solid red 1px;
color: red;
padding: 0.25em;
}
.formerror:empty {
border: solid blue 1px;
padding: 0em;
}
<form action="/detail" method="POST" role="form" name="index" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required minlength="3" />
<span class="formerror"></span>
<br />
<label for="phone_number">Mobile:</label>
<input type="number" name="phone_number" placeholder="enter your mobile number" required minlength="10" maxlength="10">
<span class="formerror"></span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="enter your password" required minlength="4" />
<span class="formerror"></span>
<br />
<button id="btnsubmit" class="btn" type="submit">Submit</button>
</form>
英文:
I changed your validation to use a sibling error message selected by a class selector, added some classes and CSS for that. Not perfect but shows how. Here I used the change event to clear the error.
Note I also added some validation attributes like minlength
etc.
Many areas can be improved and made more robust here.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function getNextSibling(elem, selector) {
//next sibling element
let sibling = elem.nextElementSibling;
//No selector, return the first sibling
if (!selector) return sibling;
// Sibling matches selector, use it; no? next sibling and continue loop
while (sibling) {
if (sibling.matches(selector)) {
return sibling;
}
sibling = sibling.nextElementSibling;
}
};
function clearErrors() {
let errors = document.getElementsByClassname('formerror');
for (let item of errors) {
item.textContent = "";
}
}
function seterror(element, error) {
let errSib = getNextSibling(element, '.formerror');
errSib.textContent = error;
}
function validateForm(event) {
event.preventDefault();
let returnval = true;
//performs validation and if validation fails, set the value of returnval to false.
let field = document.forms['index']["name"];
let name = field.value;
if (name.length < 3) {
seterror(field, "Length of name of too short");
returnval = false;
} else {
seterror(field, "");
}
field = document.forms['index']["phone_number"];
let phone_number = field.value;
if (phone_number.length != 10) {
seterror(field, "Phone number should be of 10 digits");
returnval = false;
} else {
seterror(field, "");
}
field = document.forms['index']["password"];
let password = document.forms['index']["password"].value;
if (password.length < 4) {
seterror(field, "Password should be at least of 4 characters");
returnval = false;
} else {
seterror(field, "");
}
return returnval;
}
document.forms.index.addEventListener('submit', e => {
e.preventDefault();
const isValid = validateForm(e);
console.log('Submitting the form!', isValid);
//note how this only fires when you have all validation pass
// check here for an entirely valid form and then submit
// left this as something yet to be done. (check for any non-value fields; several ways to do this.
});
document.forms.index.addEventListener('invalid', e => {
e.preventDefault();
e.target.classList.add('invalid');
validateForm(e);
}, true);
document.forms.index.addEventListener('change', e => {
e.preventDefault();
e.target.classList.remove('invalid');
validateForm(e);
});
<!-- language: lang-css -->
form {
line-height: 2em;
}
.invalid {
border: solid red 1px;
}
.formerror {
border: solid red 1px;
color: red;
padding: 0.25em;
}
.formerror:empty {
border: solid blue 1px;
padding: 0em;
}
<!-- language: lang-html -->
<form action="/detail" method="POST" role="form" name="index" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required minlength="3" />
<span class="formerror"></span>
<br />
<label for="phone_number">Mobile:</label>
<input type="number" name="phone_number" placeholder="enter your mobile number" required minlength="10" maxlength="10">
<span class="formerror"></span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="enter your password" required minlength="4" />
<span class="formerror"></span>
<br />
<button id="btnsubmit" class="btn" type="submit">Submit</button>
</form>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论