.Net Framework ASP.NET MVC

ASP.NET MVC クライアントサイドの検証機能

2017年5月17日

ASP.NET MVC のクライアントサイドの検証機能を実装する例です。

前提として、ASP.NET MVC プロジェクトの App_Start/BundleConfig.cs にある RegisterBundles メソッドに jquery.validate.js が登録されていることを確認します。

public static void RegisterBundles(BundleCollection bundles)
{
...

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));

また、_Layout.cshtml や表示するビューに jquery.validate.js が参照追加されていることを確認します。

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.
Render("~/bundles/bootstrap")
@
RenderSection("scripts", required: false)

それでは簡単にモデルクラスを用意します。
Person クラスのプロパティにデータアノテーションを指定します。Required は必須入力項目となります。Range は引数で指定された数値の範囲を有効な値として取ります。ここの例にある Age プロパティでは 5 から 80 までが有効な値になります。

namespace ValidationTest.Models
{
public class Person
{
[Required(ErrorMessage = "入力が必須です。")]
public int ID { get; set; }

[Required(ErrorMessage = "入力が必須です。")]
public string Name { get; set; }

[Required(ErrorMessage = "入力が必須です。")]
[Range(5, 80, ErrorMessage ="5 から 80 の数値を入力下さい。")]
public int Age { get; set; }
}
}

Person クラスのインスタンスを生成します。

namespace ValidationTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Person p = new Person();
p.ID = 1;
//p.Name = "toshihiko";
p.Age = 19;

return View(p);
}

...
}
}

続いて、View 側でモデルを表示するユーザーコントロールを定義します。

@model ValidationTest.Models.Person
...

@using (Html.BeginForm())
{
<div class="form-horizontal">
Person
       <div class="form-group">
@Html.LabelFor(model => model.ID, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.EditorFor(model => model.ID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ID, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-1" })
<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.Age, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-1">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}

ID、Name、Age 項目それぞれに入力検証が行われるようになりました。エラー状態では Save ボタンによるフォーム送信ができない状態になっています。

-.Net Framework, ASP.NET MVC