简体   繁体   English

当它们所代表的错误发生时,将插入错误消息

[英]where the error messages will be inserted when the errors that they represent occur

I'm having an issue figuring out how to write the following code: the problem is that I'm using an empty <div> with the id error-display. 我有一个问题,想弄清楚如何编写以下代码:问题是我正在使用带有id error-display的空<div> This <div> is where the error messages will be inserted when the errors that they represent occur. <div>是在它们表示的错误发生时将插入错误消息的位置。 I want to make all fields validated when the user clicks off of them to the next field. 我想在用户点击它们到下一个字段时验证所有字段。 If there's an error, an error message should be displayed. 如果出现错误,则应显示错误消息。 Likewise, error messages should be removed when the user fixes the problem. 同样,当用户修复问题时,应删除错误消息。 yet I'm not sure how to do it! 但我不知道怎么做! here is what I got so far: 这是我到目前为止所得到的:

    <div id="error-display">
  </div>
    <form id="project-form">
        <br>E-mail:<span class="error">* </span>
        <input type="email" name="email" id="email" placeholder="Example@example.com" required>
        <br>Password:<span class="error">* </span>
        <input type="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"  id="password" required>
        <br>Confirm Password:<span class="error">* </span>
        <input type="password" placeholder="Repeat Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"  id="password-confirmation"  required>

After inserting the emipty "div id="error-display">" what can I do? 插入emipty“div id =”错误显示“>”后,我该怎么办? lets say the error message is: Invalid email address. 让我们说错误信息是:无效的电子邮件地址。

<input type="email" name="email" id="email" placeholder="Example@example.com" required>

I tried "required" in the input elements and it's working for my inputs, however, I think my professor is looking for a different solution. 我在输入元素中尝试了“必需”并且它正在为我的输入工作,但是,我认为我的教授正在寻找一种不同的解决方案。

我建议你为每个输入字段添加change事件监听器并验证它们中的每一个,如果有些是无效的,你应该将'error- innerText属性设置为错误消息文本

Here's a quick and simple solution for you 这是一个快速简单的解决方案

in all of your input fields, put onchange="validateField(fieldID, fieldname)" like this 在所有输入字段中,像这样放置onchange="validateField(fieldID, fieldname)"

<input type="email" name="email" id="email" onchange="validateField('email', 'Email')"  placeholder="Example@example.com" required>

then paste this script below your form (or you can have this in a separate js file) 然后将此脚本粘贴到您的表单下方(或者您可以将其放在单独的js文件中)

<script>
   function validateField(fieldID, fieldname) {
     var inpObj = document.getElementById(fieldID);
       if (!inpObj.checkValidity()) {
         document.getElementById("error-display").innerHTML = "Invalid " + fieldname + ":" + inpObj.validationMessage;
       } else {
         //this will clear your error if the input is already correct
         document.getElementById("error-display").innerHTML = "";
       } 
   }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM