Asp.net MVC 表單輸入的驗證加上高亮顯示(五)

說明

表單有很多個欄位需要填寫,所以要在送出表單前做一個驗證,確認送出去的資料是符合格式的,例如信箱的格式,就需要含有@,以及這個表單是要每個欄位的填寫才能送出的,因此這篇就是要加入驗證的條件,以及顯示驗證Error 時用紅色的表示,原本用紅色表示,因為vs 版本的關係,有些地方可能寫法不太相同,一直顯示不出來,後來重新安裝 vs2019 和 .net framework 4.5 就可以執行沒有問題了。

操作流程

加入欄位的驗證條件

  • GuestResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Party1.Models
{
    public class GuestResponse
    {
        [Required(ErrorMessage ="Please enter ur name ") ]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter ur email")]
        [RegularExpression(".+\\@.+\\..+",ErrorMessage ="Please enter a valid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage ="Please enter ur phone number")]
        public string Phone { get; set; }

        [Required(ErrorMessage ="Please specify whether you'll attend")]
        public bool? WillAttend { get; set; }
    }
}

條件已經設定好,之後如果通過驗證就到 thanks 那頁,不通過就還是顯示原來的這頁

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Party1.Models;

namespace Party1.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            int hour = DateTime.Now.Hour;
            ViewBag.Greeting = hour < 12 ? "Good morning" : "Good afternoon";
            return View();
        }

        [HttpGet]
        public ViewResult RsvpForm()
        {
            return View();
        }

        [HttpPost]
        public ViewResult RsvpForm(GuestResponse guestResponse)
        {
            if (ModelState.IsValid)
            {
                //To do : email response to the party erganize
                return View("Thanks", guestResponse);
            }
            else {
                return View();
            }
        }

    }
}

Demo 顯示驗證

紀錄中間抓 bug

原本這個部分一直做失敗,如同上面說的,這裡想在多紀錄做失敗未顯示出紅色的時候,如何去 debug

在網頁模式下,按 F12 去看 console 有沒有錯誤代碼,或是從 F12 底下去看代碼,旁邊也可以選擇 cs 的去看

接下來要讓驗證的字顯示成紅色的

新增一個樣式表

  • Stylesheet1.css
.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}

.validation-summary-errors {
    font-weight: bold;
    color: #f00
}

.validation-summary-valid {
    display: none
}

建立好樣式表,要在表格那頁的 html 引入 cs

@model Party1.Models.GuestResponse
@{
    Layout = null;
}

<!--DOCTYPE html -->



    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" type="text/css" href="~/Content/StyleSheet1.css">
    <title> RsvpForm</title>



    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <p> Your name : @Html.TextBoxFor(x =&gt; x.Name) </p>
        <p> Your email: @Html.TextBoxFor(x =&gt; x.Email)</p>
        <p> Your phone : @Html.TextBoxFor(x=&gt; x.Phone)</p>

        <p>will u attend?
            @Html.DropDownListFor(x=&gt;x.WillAttend,new[]{
           new SelectListItem(){Text="Yes,I'll be there",Value=bool.TrueString},
           new SelectListItem(){Text="No,I can't come.",Value=bool.FalseString}},
           "Choose an option" )

        </p>
        <input type="submit" value="Submit RSVP">
        }

Demo

留言