繁体   English   中英

如何在前端和后端验证必填字段

[英]How to validate mandatory fields in the front-end and back-end

我正在创建我的表单,我需要对一些在前面和后面都是强制性的字段进行一些验证,并且在正确填写之前不允许发送。

以下是带有字段的表单。

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <form> <div id="informacionTicket" class="user"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h4 class="m-0 font-weight-bold text-primary"> Applicant</h4> </div> <div class="card-body"> <div class="mb-4"> <div class="form-group"> <label for="ticketIdAppliInput">Id:</label> <input maxlength="9" required id="ticketIdAppliInput" type="text" name="matricula" onkeypress="if (isNaN(String.fromCharCode(event.keyCode))) return false;" class="form-control form-control-user" /> </div> <div class="form-group"> <label for="ticketNameAppliInput">Full name:</label> <input maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user" /> </div> <div class="form-group"> <label for="ticketEmailAppliInput">Email:</label> <input maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user" /> </div> </div> </div> </div> </div> </form> <button type="button" id="submit" class="btn btn-primary btn-user btn-block">Send</button>

下面是发送数据的JavaScript function。

function f_submitForm() {
    form.append("ticketIdAppliInput", document.getElementById("ticketIdAppliInput").value);
    form.append("ticketNameAppliInput", document.getElementById("ticketNameAppliInput").value);
    form.append("ticketEmailAppliInput", document.getElementById("ticketEmailAppliInput").value);
}

更新:

添加最小可重现示例,形成 controller

[HttpPost]
public JsonResult CreateNewTicket()
        {
            var ticketIdAppliInput = Request.Form["ticketIdAppliInput"];
            var ticketNameAppliInput = Request.Form["ticketNameAppliInput"];
            var ticketEmailAppliInput = Request.Form["ticketEmailAppliInput"];

        try
        {
            using (var scope = new TransactionScope())
            {               
                var ticket = new TK_HD_TICKETS
                {
                    CUSTOMER_ID = ticketIdAppliInput,
                    CUSTOMER_FULLNAME = ticketNameAppliInput,
                    CUSTOMER_EMAIL = ticketEmailAppliInput,
                    };
                    var result = ticketCreate.CreateNewTicket(ticket);

                    // If the ticket was not saved, the transaction is finished and we return the error message
                    if (!result.Success)
                    return Json(new TicketResult
                    {
                        IsValid = false,
                        Error = "The ticket could not be created, please try again."
                    });
            }
        }catch (DbEntityValidationException ex)
        {
            // Failed to try to register data in the database
            foreach (var e in ex.EntityValidationErrors)
            foreach (var validationError in e.ValidationErrors)
                Console.WriteLine("Property: " + validationError.PropertyName + " Error: " +
                                  validationError.ErrorMessage);

            return Json(new TicketResult
            {
                IsValid = false,
                Error = "There was an error creating the ticket, please try again."
            });
        }
        }

自己创建一个 model class:

public class MyData {
  [Required]
  [StringLength(9)]
  [Display(Name="Id")]
  public string ticketIdAppliInput {get;set;}
  [Required]
  public string ticketNameAppliInput {get;set;}
  [Required]
  public string ticketEmailAppliInput {get;set;}
}

更改您的 controller 以将此 class 作为输入:

[HttpPost]
public ActionResult CreateNewTicket(MyData data) {
  if (ModelState.IsValid)
    return Json(...);
  return View(data);
}

然后更改您的视图以实际使用此 class (我将为您做第一个输入):

@model MyData
@using (Html.BeginForm())
{
  <div id="informacionTicket" class="user">
    <div class="card shadow mb-4">
      <div class="card-header py-3">
        <h4 class="m-0 font-weight-bold text-primary">
          Applicant</h4>
      </div>
      <div class="card-body">
        <div class="mb-4">
          <div class="form-group">
            @Html.LabelFor(model=>model.ticketIdAppliInput)
            @Html.TextboxFor(model=>model.ticketIdAppliInput, new { @type="text", @class="form-control form-control-user"})
            @Html.ValidationMessageFor(model=>model.ticketIdAppliInput)
          </div>
          <div class="form-group">
            <label for="ticketNameAppliInput">Full name:</label>
            <input maxlength="100" id="ticketNameAppliInput" type="text" name="nombre" class="form-control form-control-user" />
          </div>
          <div class="form-group">
            <label for="ticketEmailAppliInput">Email:</label>
            <input maxlength="100" id="ticketEmailAppliInput" type="email" name="email" class="form-control form-control-user" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <button type="button" id="submit" class="btn btn-primary btn-user btn-block">Send</button>
}

在 Html 中,您可以简单地使用所需的标签,并且有很多 jquery 库将为您提供验证以及显示弹出自定义消息。

暂无
暂无

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

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