ViewModel 中使用的基本驗證屬性

模型

using System.ComponentModel.DataAnnotations;

public class ViewModel
{
    [Required(ErrorMessage="Name is required")] 
    public string Name { get; set; }

    [StringLength(14, MinimumLength = 14, ErrorMessage = "Invalid Phone Number")]
    [Required(ErrorMessage="Phone Number is required")] 
    public string PhoneNo { get; set; }

    [Range(typeof(decimal), "0", "150")]
    public decimal? Age { get; set; }

    [RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code.")]
    public string ZipCode {get;set;}

    [EmailAddress(ErrorMessage = "Invalid Email Address")] 
    public string Email { get; set; }

    [Editable(false)] 
    public string Address{ get; set; }
}

檢視

// Include Jquery and Unobstructive Js here for client side validation

@using (Html.BeginForm("Index","Home") { 

    @Html.TextBoxFor(model => model.Name) 
    @Html.ValidationMessageFor(model => model.Name)

    @Html.TextBoxFor(model => model.PhoneNo)
    @Html.ValidationMessageFor(model => model.PhoneNo)

    @Html.TextBoxFor(model => model.Age)
    @Html.ValidationMessageFor(model => model.Age)

    @Html.TextBoxFor(model => model.ZipCode)
    @Html.ValidationMessageFor(model => model.ZipCode)

    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)

    @Html.TextBoxFor(model => model.Address)
    @Html.ValidationMessageFor(model => model.Address)

    <input type="submit" value="submit" />
}

調節器

public ActionResult Index(ViewModel _Model) 
{ 
    // Checking whether the Form posted is valid one. 
    if(ModelState.IsValid) 
    { 
        // your model is valid here.
        // perform any actions you need to, like database actions,
        // and/or redirecting to other controllers and actions.
    }
    else 
    {
        // redirect to same action
        return View(_Model);
    } 
}