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

时间:2019-09-18 23:03:18

标签: javascript c# html asp.net-mvc

我正在创建表单,我需要对某些字段进行一些验证,这些字段在前面和后面都是必需的,并且只有在正确填写后才能发送。

以下是带有字段的表格。

<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 f_submitForm() {
    form.append("ticketIdAppliInput", document.getElementById("ticketIdAppliInput").value);
    form.append("ticketNameAppliInput", document.getElementById("ticketNameAppliInput").value);
    form.append("ticketEmailAppliInput", document.getElementById("ticketEmailAppliInput").value);
}

更新:

添加最少的可复制示例,表单控制器

[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."
            });
        }
        }

2 个答案:

答案 0 :(得分:2)

创建一个模型类:

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;}
}

更改控制器以将此类作为输入:

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

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

@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>
}

答案 1 :(得分:0)

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