表单在按钮点击时提交而不显示错误。

huangapple go评论91阅读模式
英文:

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

&lt;form action=&quot;/detail&quot; method=&quot;POST&quot; role=&quot;form&quot; name=&quot;index&quot; onsubmit=&quot;return validateForm()&quot; enctype=&quot;application/x-www-form-urlencoded&quot;&gt;
    &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Enter your name&quot; required/&gt;
    &lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
    &lt;br /&gt;
    &lt;label for=&quot;phone_number&quot;&gt;Mobile:&lt;/label&gt;
    &lt;input type=&quot;number&quot; name=&quot;phone_number&quot; placeholder=&quot;enter your mobile number&quot; required &gt;
    &lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
    &lt;br/&gt;
    &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
    &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;enter your password&quot; required  /&gt;
    &lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
    &lt;br /&gt;
    &lt;button id=&quot;btnsubmit&quot; class=&quot;btn&quot; onclick=&quot;submit&quot;&gt;Submit&lt;/button&gt;

code for form validation

&lt;script&gt;
    function clearErrors(){
        errors=document.getElementsByClassname(&#39;formerror&#39;);
        for(let item of errors){
            item.innerHTML=&quot;&quot;;
        }
    }
    function seterror(id,error){
        //sets error inside tag of id
        element=document.getElementById(id);
        element.getElementsByClassName(&#39;formerror&#39;)[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[&#39;index&#39;][&quot;name&quot;].value;
        if(name.length&lt;3)
        {
            seterror(&quot;name&quot;,&quot;length of name of too short&quot;);
            returnval=false;
        }
        var phone_number = document.forms[&#39;index&#39;][&quot;phone_number&quot;].value;
        if(phone_number.length!=10)
        {
            seterror(&quot;phone_number&quot;,&quot;phone number should be of 10 digits&quot;);
            returnval=false;
        }
        var password = document.forms[&#39;index&#39;][&quot;password&quot;].value;
        if(password.length&lt;4)
        {
            seterror(&quot;password&quot;,&quot;password should be at least of 4 characters&quot;);
            returnval=false;
        }
        return returnval;
    }
&lt;/script&gt;

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=&quot;3&quot; for the name and pattern=&quot;[0-9]{10}&quot; 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=&quot;3&quot; for the name and pattern=&quot;[0-9]{10}&quot; 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(&#39;submit&#39;, e =&gt; {
  e.preventDefault();
  console.log(&#39;Submitting the form!&#39;);
});

document.forms.index.addEventListener(&#39;invalid&#39;, e =&gt; {
  e.preventDefault();
  e.target.classList.add(&#39;invalid&#39;);
}, true);

document.forms.index.addEventListener(&#39;input&#39;, e =&gt; {
  e.preventDefault();
  e.target.classList.remove(&#39;invalid&#39;);
});

<!-- language: lang-css -->

span.formerror {
  display: none;
}

input.invalid ~ span.formerror {
  display: inline;
}

<!-- language: lang-html -->

&lt;form action=&quot;/detail&quot; method=&quot;POST&quot; role=&quot;form&quot; name=&quot;index&quot; enctype=&quot;application/x-www-form-urlencoded&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt;
  &lt;input type=&quot;text&quot; name=&quot;name&quot; minlength=&quot;3&quot; placeholder=&quot;Enter your name&quot; required&gt;
  &lt;span class=&quot;formerror&quot;&gt;length of name of too short&lt;/span&gt;
  &lt;br /&gt;
  &lt;label for=&quot;phone_number&quot;&gt;Mobile:&lt;/label&gt;
  &lt;input type=&quot;tel&quot; name=&quot;phone_number&quot; pattern=&quot;[0-9]{10}&quot; placeholder=&quot;enter your mobile number&quot; required&gt;
  &lt;span class=&quot;formerror&quot;&gt;phone number should be of 10 digits&lt;/span&gt;
  &lt;br/&gt;
  &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
  &lt;input type=&quot;password&quot; name=&quot;password&quot; minlength=&quot;3&quot; placeholder=&quot;enter your password&quot; required &gt;
  &lt;span class=&quot;formerror&quot;&gt;password should be at least of 4 characters&lt;/span&gt;
  &lt;br /&gt;
  &lt;button class=&quot;btn&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;

<!-- 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(&#39;formerror&#39;);
for (let item of errors) {
item.textContent = &quot;&quot;;
}
}
function seterror(element, error) {
let errSib = getNextSibling(element, &#39;.formerror&#39;);
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[&#39;index&#39;][&quot;name&quot;];
let name = field.value;
if (name.length &lt; 3) {
seterror(field, &quot;Length of name of too short&quot;);
returnval = false;
} else {
seterror(field, &quot;&quot;);
}
field = document.forms[&#39;index&#39;][&quot;phone_number&quot;];
let phone_number = field.value;
if (phone_number.length != 10) {
seterror(field, &quot;Phone number should be of 10 digits&quot;);
returnval = false;
} else {
seterror(field, &quot;&quot;);
}
field = document.forms[&#39;index&#39;][&quot;password&quot;];
let password = document.forms[&#39;index&#39;][&quot;password&quot;].value;
if (password.length &lt; 4) {
seterror(field, &quot;Password should be at least of 4 characters&quot;);
returnval = false;
} else {
seterror(field, &quot;&quot;);
}
return returnval;
}
document.forms.index.addEventListener(&#39;submit&#39;, e =&gt; {
e.preventDefault();
const isValid = validateForm(e);
console.log(&#39;Submitting the form!&#39;, 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(&#39;invalid&#39;, e =&gt; {
e.preventDefault();
e.target.classList.add(&#39;invalid&#39;);
validateForm(e);
}, true);
document.forms.index.addEventListener(&#39;change&#39;, e =&gt; {
e.preventDefault();
e.target.classList.remove(&#39;invalid&#39;);
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 -->

&lt;form action=&quot;/detail&quot; method=&quot;POST&quot; role=&quot;form&quot; name=&quot;index&quot; enctype=&quot;application/x-www-form-urlencoded&quot;&gt;
&lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Enter your name&quot; required minlength=&quot;3&quot; /&gt;
&lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
&lt;br /&gt;
&lt;label for=&quot;phone_number&quot;&gt;Mobile:&lt;/label&gt;
&lt;input type=&quot;number&quot; name=&quot;phone_number&quot; placeholder=&quot;enter your mobile number&quot; required minlength=&quot;10&quot; maxlength=&quot;10&quot;&gt;
&lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
&lt;br/&gt;
&lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;enter your password&quot; required minlength=&quot;4&quot; /&gt;
&lt;span class=&quot;formerror&quot;&gt;&lt;/span&gt;
&lt;br /&gt;
&lt;button id=&quot;btnsubmit&quot; class=&quot;btn&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月26日 19:15:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定