【问题标题】:Error message not displaying on Form validation表单验证中未显示错误消息
【发布时间】:2022-11-09 16:26:29
【问题描述】:

我正在创建一个使用 html razor 和 javascript 进行验证的简单表单。我必须进行的一项验证是检查空字段。

预期结果:
如果用户单击提交按钮而不在输入字段中输入任何值,则会显示错误消息(在输入字段下方)。

实际结果:
即使用户在没有在输入字段中输入任何值的情况下单击提交按钮,也不会显示错误消息。似乎 html 文件根本没有与 JS 文件通信。我尝试了各种方法,例如清除浏览器缓存和检查拼写错误,但无济于事。

以下是相关代码:

表单.cshtml

@* Display error message *@
<div id="error"></div>

<form id ="form">
    <div class="form-group">
        <label for="deviceId">Device ID</label>
        <input type="text" class="form-control" id="deviceId" placeholder="Enter Device Device ID">
    </div>
    
    @* Energy Usage *@
    <div class="form-group">
        <label for="energyUsage">Energy Usage</label>
        <input type="number" class="form-control" id="energyUsage" placeholder="Enter Energy Usage">
    </div>
    
    <button onclick="performValidation()" type="submit">Submit</button>
</form>

@section Scripts
{
    <script src="js/validation.js"></script>
}

验证.js

const deviceId = document.getElementById('deviceId')
const energyUsage = document.getElementById('energyUsage')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')

function performValidation()
{
    form.addEventListener('submit', (e) => {

        // list to store the error messages
        let messages = []

        // if device ID field is an empty string or user did not pass in any device Id
        if (deviceId.value === ' ' || deviceId.value == null) {
            // send the error message
            messages.push('Device ID is required')
            // console.log('No Device ID retrieved')
        }

        // if there is error, prevent the form from submitting
        if (messages.length > 0) {
            e.preventDefault()

            // check errorElement
            errorElement.innerText = messages.join(', ') // to separate error elements from each other
        }
    })
}

【问题讨论】:

  • 尝试检查输入值是否为空字符串:deviceId.value === ''。您实际上检查了一个空格或null(这永远不会发生)。
  • Console 是你的朋友!

标签: javascript html razor


【解决方案1】:

检查空字符串时删除空格:

验证.js

if (deviceId.value === '' || deviceId.value == null)

将 html 文件正确路由到 js 文件:

表单.cshtml

<script src="~/js/validation.js"></script>

【讨论】:

    【解决方案2】:

    试试这个代码以获得一个想法。

    <script>
    form_validation();
    
    function form_validation() {
      const formName = document.getElementsByName('form-name')[0];
      const fieldsArray = Array.from(formName.elements);
    
      const span = document.createElement('span');
      span.classList.add('form-validation-error');
      formName.insertBefore(span, formName.children[0]);
    
      function validate() {
        for (let i = 0; i < fieldsArray.length; i++) {
    
          if (fieldsArray[i].value == "") {
            //console.log(fieldsArray[i]);
            const str = fieldsArray[i].previousElementSibling.innerHTML;
            span.innerHTML = `${str} can not be empty!`;
            span.style.display = 'block';
            span.style.margin = '10px 0';
            fieldsArray[i].style.border = '1px solid red';
            return false;
            break;
          } else {
            fieldsArray[i].style.border = '1px solid black';
          }
        }
        return true;
      }
    
      formName.addEventListener('submit', (e) => {
        e.preventDefault();
        if (validate()) {
          
          //formName.submit(); //uncomment this line to submit the form
          console.log('Validation pass. You can submit the form!');
        } else {
          console.log('Field is empty. Validation not pass!');
        }
      });
    } 
    </script>
    
    input {
      margin: 10px 0;
    }
    
    .form-validation-error {
      color: red;
      display: block;
    }
    
    <form action="#" method="post" name="form-name">
      <label for="fname">First Name</label>
      <input name="fname" value="">
      <br/>
      <label for="fname">Last Name</label>
      <input name="lname" value="">
      <br/>
      <input type="hidden" name="form_submit" value="1">
      <input type="submit" value="Submit Form">
      </form
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2022-06-20
      相关资源
      最近更新 更多