📜  ASP.Net MVC验证

📅  最后修改于: 2020-12-28 00:51:50             🧑  作者: Mango

ASP.NET MVC输入验证

验证用户输入是应用程序程序员的必要任务。应用程序应仅允许有效的用户输入,以便我们仅获得所需的信息。

ASP.NET MVC框架提供了可以应用于模型属性的内置注释。它验证输入并向用户显示适当的消息。

常用验证批注

Annotations Description
Required It is used to make a required field.
DisplayName It is used to define the text we want to display for the fields.
StringLength It defines a maximum length for a string field.
Range It is used to set a maximum and minimum value for a numeric field.
Bind It lists fields to exclude or include when binding parameter or form values to model properties.
ScaffoldColumn It allows hiding fields from editor forms.
MaxLength It is used to set max length for a field.
EmailAddress It is used to validate email address.
DataType It is used to specify data type for the field.
RegularExpression It is used to associate regular expression for a field.

让我们创建一个示例,该示例将通过使用批注来验证输入。为了创建示例,首先我们要创建一个StudentController ,然后是Student Model。

控制者

// StudentsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
    public class StudentsController : Controller
    {
        // GET: Students
        public ActionResult Index()
        {
            return View();
        }
    }
}

模型

// Student.cs

using System.ComponentModel.DataAnnotations;

namespace MvcApplicationDemo.Models
{
    public class Student
    {
        public int ID { get; set; }
        // -- Validating Student Name
        [Required(ErrorMessage ="Name is required")]
        [MaxLength(12)]
        public string Name { get; set; }
        // -- Validating Email Address
        [Required(ErrorMessage ="Email is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }
        // -- Validating Contact Number
        [Required(ErrorMessage = "Contact is required")]
        [DataType(DataType.PhoneNumber)]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]
        public string Contact { get; set; }
    }
}

视图

// Index.cshtml

@model MvcApplicationDemo.Models.Student
@{
    ViewBag.Title = "Index";
}

Index

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

Student


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

输出:

要查看输出,请右键单击Index.cshtml文件,然后在浏览器中选择“查看”。这将产生以下结果。

如我们所见,它可以验证表单字段并向用户显示错误消息。在下面的屏幕截图中,我们正在验证输入的数据是否符合预期。