jquery 客户端下拉验证在razor AJAX

wkftcu5l  于 2023-03-01  发布在  jQuery
关注(0)|答案(1)|浏览(163)

我有一个表单,我有多个文本框和下拉框
我的看法如下

<form id="canditateForm" asp-action="CreateCanditae" method="post">
            @*<form id="canditateForm">*@
            <div class="row" rowspan="2">
            
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <div class="col-sm-2 form-group">
                        <label asp-for="EmployeePrefix">Prefix</label>
                    <select asp-for="EmployeePrefix" id="empprefix" name="emplprefix" class="form-control" asp-items="@ViewBag.prefix">
                        </select>
                        <span asp-validation-for="EmployeePrefix" class="text-danger"></span>
                    </div>
                    &nbsp;
                    <div class="col-sm-4 form-group">
                        <label asp-for="EmployeeFirstName">Canditate First Name</label>
                    <input asp-for="EmployeeFirstName" type="text" id="empfirstname" class="form-control" placeholder="Canditate Name (As per AADHAR)" required>
                        <span asp-validation-for="EmployeeFirstName" class="text-danger"></span>
                    </div>
                    &nbsp;
                    <div class="col-sm-4 form-group">
                        <label asp-for="EmployeeLastName">Canditate Last Name</label>
                    <input asp-for="EmployeeLastName" id="emplasttname" type="text" class="form-control" placeholder="Canditate Name (As per AADHAR)" required>
                        <span asp-validation-for="EmployeeLastName" class="text-danger"></span>
                    </div>
                    &nbsp;
            </div>
            <div class="row" rowspan="2">
                    <div class="col-sm-3 form-group">
                        <label asp-for="EmployeeGender">Gender</label>
                        <select asp-for="EmployeeGender" id="empgender" class="form-control" asp-items="@ViewBag.gender">
                        </select>
                        <span asp-validation-for="EmployeeGender" class="text-danger"></span>
                    </div>
                    &nbsp;
                    <div class="col-sm-3 form-group">
                        <label asp-for="EmployeeMaritalStatus">Marital Status</label>
                        <select asp-for="EmployeeMaritalStatus" id="empmaritalstatus" class="form-control" asp-items="@ViewBag.maritalstatus"></select>
                        <span asp-validation-for="EmployeeMaritalStatus" class="text-danger"></span>
                    </div>
                    
            </div>
                    <div class="col-sm-6 form-group">
                <input style="background-color:lightgreen;" type="submit" value="Create" onclick="savecanditateinfo()" class="form-control" />
                @*<input style="background-color:lightgreen;"  value="Create" onclick="savecanditateinfo()" class="form-control" />*@
                    </div>
                    <div class="col-sm-6 form-group">
                        <a asp-action="Index">Back to List<span style="font-size:large;"></span></a>
                    </div>
                    @if (TempData["msg"] != null)
                    {
                        <div class="err">@TempData["msg"]</div>
                    }
                    @if (ViewBag.Message != null)
                    {
                        <script type="text/javascript">
                            window.onload = function () {
                                alert("@ViewBag.Message");
                            };
                        </script>
                    }
        </form>

我现在使用jQuery验证整个表单,方法是在客户端的form标记中放置if,jQuery如下所示。

<script>
        $(document).ready(function () 
        {
            $.validator.unobtrusive.parse($("#canditateForm"));
        })

        

        function savecanditateinfo() 
        {
            if ($("#canditateForm").valid()) 
            {
                var formData = $("#canditateForm").serialize();
                console.log(formData);
                    $.ajax(
                        {
                            dataType: 'xhr',
                            url: "/HRDashboard/CreateCanditae",
                            type: "POST",
                            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                            data: formData,
                                success: function (response) {
                                //alert(response);
                                },
                                error: function (request, status, error) {
                                //alert(request.responseText);
                                }

                        }
                     );
            }
        }
    </script>

我能够验证客户端本身的文本框,但对于下拉框,现在我需要点击服务器来验证它。我通过视图包传递下拉列表,我的模型如下

public partial class EmployeeBasicInformation
    {
        public int EmployeeId { get; set; }

        [Required]
        [ValidPrefix(ErrorMessage =
            "Prefix can not be epmty")]
        public int? EmployeePrefix { get; set; }

        [RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid First name")]
        public string? EmployeeFirstName { get; set; }

        [RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid last name")]
        public string? EmployeeLastName { get; set; }

        [ValidGender(ErrorMessage =
            "Gender can not be epmty")]
        public int? EmployeeGender { get; set; }

        [Validmaritalstatus(ErrorMessage =
            "MaritalStatus can not be epmty")]
        public int? EmployeeMaritalStatus { get; set; }

我甚至尝试添加所需的数据注解属性到模型,但我仍然可以使它在客户端验证。请指导。

nx7onnlm

nx7onnlm1#

根据您的问题,我认为在下拉列表中,您将占位符设置为空值,当用户没有手动选择任何选项并提交表单时,前端验证将不会验证下拉列表的值,对吗?
我不知道你的自定义数据注解属性是什么,比如[ValidGender],但是从错误信息来看,我认为它像是默认的[required]属性,所以在这里我使用[required]属性和默认的验证js来创建一个工作演示。

public class TestModel
    {
        public string Name { get; set; }
        [Required(ErrorMessage =
            "Gender can not be epmty")]
        public int? EmployeeGender { get; set; }
    }
    • 主计长**
public IActionResult Test()
        {
            var test = new List<SelectListItem>();
           
            test.Add(new SelectListItem()
            {
                Text = "male",
                Value = "0"
            });
            test.Add(new SelectListItem()
            {
                Text = "female",
                Value = "1"
            });

            ViewBag.gender = test;

            return View();
        }
    • 查看**
@model TestModel

<form method="post" id="canditateForm">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="col-sm-2 form-group">
        <label asp-for="Name">Prefix</label>
        <input asp-for="Name" type="text"  class="form-control" placeholder="Canditate Name (As per AADHAR)" required>
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="col-sm-4 form-group">
        <label asp-for="EmployeeGender">Canditate Last Name</label>
         <select asp-for="EmployeeGender" id="empgender" class="form-control" asp-items="@ViewBag.gender">
            <option value="">--Please Select your Gender---</option>
         </select>
        <span asp-validation-for="EmployeeGender" class="text-danger"></span>
    </div>

    <input style="background-color:lightgreen;" type="submit" value="Create" onclick="savecanditateinfo()" class="form-control" />
</form>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }

    <script>
        function savecanditateinfo()
        {
            if ($("#canditateForm").valid())
            {
                var formData = $("#canditateForm").serialize();
                console.log(formData);
                    $.ajax(
                        {
                            dataType: 'xhr',
                            url: "/Test/test",
                            type: "POST",
                            //headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                            data: formData,
                                success: function (response) {
                                //alert(response);
                                },
                                error: function (request, status, error) {
                                //alert(request.responseText);
                                }

                        }
                     );
            }
        }
    </script>
}
    • 演示:**

相关问题