【问题标题】:How do I do an Input validation in cshtml?如何在 cshtml 中进行输入验证?
【发布时间】:2021-09-11 02:15:48
【问题描述】:

我正在尝试进行输入验证,以便让用户输入一个数字,并且我想检查它是否是一个数字。当我单击提交按钮时,我希望它检查它是否是一个数字。如果是我想要一条消息说成功添加,否则一条错误消息说请输入有效数字。这是我目前用于输入文本框和提交按钮的代码。我将如何继续添加验证和错误消息?

<div class="form-group">
    <input class="form-control" id="hours" name="hours" type="text" pattern="\d{1,2}" title="NumberOfHoursAlloted" value=@ViewBag.Hours>
    <input class="btn btn-block" type="submit" onclick="verifyCheckboxes()" value="Submit" />
</div>

【问题讨论】:

    标签: html css asp.net visual-studio razor


    【解决方案1】:

    至少在 google chrome pattern="\d{1,2}" 上应该只允许您插入数字 1 或 2。请参阅下面的代码。使用 javascript,这是查看您是否输入了数字。为此,我使用isNaN() Function。您可以通过以下链接了解更多信息:https://www.w3schools.com/jsref/jsref_isnan.asp

    myform = document.getElementById('myform');
    myform.addEventListener('submit', verifyCheckboxes);
    function verifyCheckboxes(e)
    {
        let user_value = document.getElementById("hours").value;
         
        if(isNaN(user_value))//determines whether a value is an illegal number
      {
        document.getElementById("demo").innerHTML = "Please enter a numaric value";
        e.preventDefault();//This will prevent the form from going to action_page.php
      }
      else
      {
        alert("Your input is valid. Redirecting you to action_page.php");
      }
    }
    <form id="myform" action="/action_page.php">
      <label>Enter number of hours:</label>
      <input class="form-control" id="hours" name="hours" type="text" title="NumberOfHoursAlloted"> 
      <div style="color: red" id="demo"></div>
      <input class="btn btn-block" type="submit" value="Submit">
    </form> 

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 2019-12-09
      • 2017-03-19
      相关资源
      最近更新 更多