jquery 如何在ASP.NETMVC中为模态添加表单验证?

qlvxas9a  于 11个月前  发布在  jQuery
关注(0)|答案(3)|浏览(154)

我需要在一个有必填字段的模式中创建一个表单。用户必须只允许在必填字段被填充后提交表单,如果它为空,则必须显示错误消息。我们如何才能实现这一点?

z0qdvdin

z0qdvdin1#

客户端验证会在表单有效之前阻止提交。“提交”按钮会运行JavaScript,它会提交表单或显示错误消息。
尝试添加:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>

字符串
下面是一个demo,你可以参考一下:

@model    RabiesClinics.Models.Item

<button id="btnShowModal" type="button"> Upload </button>
<div class="modal fade" id="Modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button id="btnHideModal" type="button" class="btn btn-secondary" data-dismiss="modal">  ×</button>
            </div>
            <div class="modal-body">
                <form asp-action="Index">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

                    <div class="form-group">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    

                    <div class="form-group">
                        <input type="submit" value="submit" class="btn btn-primary" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnShowModal").click(function () {

            $("#Modal").modal('show');
        });
        $("#btnHideModal").click(function () {
            $("#Modal").modal('hide');
        });
    });

</script>


项目:

public class Item
{
    [Required]
    public string Name { get; set; }    
    
}


结果:


的数据
您可以阅读客户端验证以了解更多信息。

du7egjpx

du7egjpx2#

如果你想使用服务器端验证,你可以在绑定到表单的模型类上使用数据注解。例如,你可以像下面的类一样验证模型:

public class TransactionModel
{
 [Key]
 public int TransactionID { get; set; }

[MaxLength(12)]
[Required(ErrorMessage ="This field is required.")]
[DisplayName("Account Number")]
[Column(TypeName ="nvarchar(12)")]
public required string AccountNumber { get; set; }

[Required(ErrorMessage = "This field is required.")]
[DisplayName("Beneficiary Name")]
[Column(TypeName = "nvarchar(12)")]
public required string BeneficiaryName { get; set; }

[Required(ErrorMessage = "This field is required.")]
[DisplayName("Bank Name")]
[Column(TypeName = "nvarchar(12)")]
public required string BankName { get; set; }

[MaxLength(11)]
[Required(ErrorMessage = "This field is required.")]
[DisplayName("SWIFT Code")]
[Column(TypeName = "nvarchar(12)")]
public required string SWIFTCode { get; set; }

[Required(ErrorMessage = "This field is required.")]
public int Amount { get; set; }

public DateTime Date { get; set; }
}

字符串
但是如果你想要客户端验证,你可以使用Qing Guo给出的解决方案。你可以在JavaScript或jQuery中将提交处理程序绑定到你的表单并应用你的验证。有一些jQuery插件也可以在你的前端绑定,你只需要传递你的字段(id或类)和验证消息,它就会处理你的验证。示例:https://jqueryvalidation.org/

hfsqlsce

hfsqlsce3#

要实现这一点,您可以使用HTML,CSS和JavaScript/jQuery的组合。下面是一个示例代码片段,演示了如何在模态中创建一个具有必填字段的表单并实现您所描述的功能:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modal Form Example</title>
    <style>
        /* Add your CSS styling for the modal and form here */
        #myModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background-color: #fff;
            border: 1px solid #ccc;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            z-index: 1;
        }

        .error-message {
            color: red;
            margin-top: 5px;
        }
    </style>
</head>
<body>

<!-- Button to open the modal -->
<button onclick="openModal()">Open Modal</button>

<!-- The Modal -->
<div id="myModal">
    <!-- Modal content -->
    <form id="myForm" onsubmit="return validateForm()">
        <label for="requiredField">Required Field:</label>
        <input type="text" id="requiredField" name="requiredField" required>
        <div class="error-message" id="error-message"></div>
        <br>
        <input type="submit" value="Submit">
    </form>
</div>

<script>
    // Function to open the modal
    function openModal() {
        document.getElementById('myModal').style.display = 'block';
    }

    // Function to close the modal
    function closeModal() {
        document.getElementById('myModal').style.display = 'none';
    }

    // Function to validate the form
    function validateForm() {
        var requiredField = document.getElementById('requiredField').value;
        var errorMessage = document.getElementById('error-message');

        // Check if the required field is empty
        if (requiredField.trim() === '') {
            errorMessage.innerHTML = 'Please fill in the required field.';
            return false; // Prevent form submission
        } else {
            errorMessage.innerHTML = ''; // Clear error message
            closeModal(); // Close the modal if the form is valid
            return true; // Allow form submission
        }
    }
</script>

</body>
</html>

字符串
在本例中,模态最初是隐藏的(display: none;)。当用户点击“打开模态”按钮时,模态变得可见。模态内的表单有一个必需的文本输入字段。当表单提交时,validateForm()函数被调用,它检查必需的字段是否为空。如果是,则显示错误消息,并且阻止表单提交。如果该字段已填充,则清 debugging 误消息,并关闭该模式。
您可以根据您的特定要求进一步自定义样式和行为。

相关问题