个性化阅读
专注于IT技术分析

asp.net mvc验证

点击下载

本文概述

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

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


常用验证批注

注解描述
Required用于填写必填字段。
DisplayName它用于定义我们要为字段显示的文本。
StringLength它定义了字符串字段的最大长度。
Range它用于为数字字段设置最大值和最小值。
Bind它列出了将参数或表单值绑定到模型属性时要排除或包含的字段。
ScaffoldColumn它允许隐藏编辑器表单中的字段。
MaxLength用于设置字段的最大长度。
EmailAddress用于验证电子邮件地址。
DataType用于指定字段的数据类型。
RegularExpression它用于关联字段的正则表达式。

让我们创建一个示例,该示例将通过使用注释来验证输入。为了创建示例,首先我们要创建一个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";
}
<h2>Index</h2>
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

输出:

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

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

赞(0)
未经允许不得转载:srcmini » asp.net mvc验证

评论 抢沙发

评论前必须登录!