MVC:对输入数据添加验证

Come from old posts in MVC:对输入数据添加验证  , 2016-08-01

数据验证是很常见的,比如网页需要你输入你的姓名,但你输入了一串数字(不知道数字是不是也可以当姓名( ▼-▼ )),这明显是不符合规则的,也不能任由这种数据存入数据存储

MVC框架里已经集成了JQuery验证功能,我们来一探究竟

1)建立数据验证条件

首先,我们看看如何给数据库条目添加限制,我还是采用用EntityFramework的独特方法来进行

打开定义好的数据实体类,比如有这些字段:

        public int ID { get; set; }

        public string Title { get; set; }

        public DateTime ReleaseDate { get; set; }

        public string Genre { get; set; }

        public decimal Price { get; set; }

        public string Rating { get; set; }

我们把他们添加标签限制如下:

        public int ID { get; set; }

        [StringLength(60,MinimumLength = 3)]
        public string Title { get; set; }


        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }


        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [Required]
        [StringLength(30)]
        public string Genre { get; set; }


        [Range(1,100)]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }


        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [StringLength(5)]
        public string Rating { get; set; }

[StringLength(*,MinimumLength = *)]:限制了字符串的最大长度和最小长度

[Display(Name = “******”)]:定义了字符串的显示名称

[DataType(******.**)]:定义了数据的存储类型

[DisplayFormat(DataFormatString = “{******}”,ApplyFormatInEditMode = true)]:定义了数据存储的格式,而且允许按照EditMode定义好的格式来显示

[RegularExpression(@”********”)]:需要匹配特定的正则表达式

[Required]:需要Value值,但比如一些值类型本身需要,就不用填了

[Range(1,100)]:值的取值范围

还有一些其他限制可以定义,可以阅读MSDN等获取具体的内容

想要数据库架构变更生效你需要这么做:

add-migration DataAnnotations
update-database

依然是在PM控制台进行,具体参考上一篇博客内容 [ MVC:Code First Migrations  ],这里不赘述了

验证规则会自动执行由.NET 框架有助于使您的应用程序更加健壮。它还确保,你不能忘验证一些东西,无意中让坏的数据到数据库

2)错误UI的显示与处理

JQuery真正的好处在于我们不需要在代码中增加哪怕一条判断信息,当信息检查不通过,是无法触发POST提交的,只会重新导行到当前页面

只需要这样组织HTML部分:

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

ValiMess部分就会按照预定检测Edit中的内容是否符合规范,当所有检测通过,当前页面状态变为Valid,才允许POST发送表单内容,并相应数据库变更:

// GET: PersonalModels/Create
        public ActionResult Create() {
            return View();
        }

        // POST: PersonalModels/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] PersonalModel personalModel) {
            if(ModelState.IsValid) {
                db.Personal.Add(personalModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(personalModel);
        }

如果想要在以后更改的验证逻辑,你可以在一个地方通过将验证属性添加到模型,而不必担心不符合规则 。 如何强制执行的应用程序的不同部分 — — 所有的验证逻辑会在一个地方定义和使用。这使代码非常干净,并使它容易维护和发展。这也意味着你会充分尊重DRY原则(单一,不重复)。

3)一些需要注意的地方

对于多浏览器支持还有些地方需要注意

1.如果你使用日期字段的DataType属性,你必须也指定 DisplayFormat属性,以确保该字段在 Chrome 浏览器中都能正确呈现

2.jQuery 验证不能与范围属性和日期时间。例如,下面的代码将始终显示客户端验证错误,即使在指定范围内的日期是︰

[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]

需要禁用 jQuery 日期验证与日期时间使用范围的属性。但通常在模型中编译硬日期不是很好的做法。

3.可以将代码放在一行上显示:

[Display(Name = “Release Date”),DataType(DataType.Date)]

603 thoughts on “MVC:对输入数据添加验证”

  1. Magnificent site. A lot of helpful information here.

    I’m sending it to some buddies ans additionally sharing in delicious.

    And of course, thanks to your effort!

  2. We are a bunch of volunteers and opening a new scheme in our community.
    Your web site provided us with valuable info to work on. You’ve performed a
    formidable activity and our whole neighborhood will likely
    be thankful to you.

  3. I drop a leave a response each time I especially enjoy a post on a site or I have something to contribute to
    the discussion. It’s triggered by the passion displayed in the article I read.
    And on this post MVC:对输入数据添加验证 – Wallace
    Sun. I was excited enough to drop a thought 😛 I do have a few questions for you
    if it’s allright. Is it only me or does it seem like a few of the comments come across like they are coming from brain dead visitors?
    😛 And, if you are writing on additional online social sites, I
    would like to follow you. Could you list the complete urls of your communal pages like your linkedin profile, Facebook page or twitter feed?

  4. You can definitely see your expertise in the work you
    write. The arena hopes for more passionate writers like
    you who aren’t afraid to say how they believe. All the time go after your heart.

  5. Zithromax For Cold Effets Secondaires Viagra Ou Cialis Cephalexin What Is It Used For cialis Doxcycline No Prescription On Line Pharmacys In India Propecia Es Mirame Que Proscar

  6. Howdy! Quick question that’s totally off topic.

    Do you know how to make your site mobile friendly? My website looks weird
    when viewing from my iphone. I’m trying to find a theme or plugin that might be able to correct this problem.
    If you have any suggestions, please share.
    Thanks!

  7. You’re so interesting! I don’t think I’ve read anything like this before.

    So nice to find somebody with some genuinne thoughts on this subject
    matter. Really.. thanks for starting this up. Thhis web ssite is one
    thin that is needed on the web, someone with some originality!

  8. Hey there! This post couldn’t be written any better!
    Reading this post reminnds me of my old room mate!
    He always kept talking about this. I will forward
    this page to him. Fairly certain he will have
    a good read. Thanks for sharing!

  9. You invest so much in your home furniture and send a great deal of time and effort choosing what seems best, but what you ignore is that there is a place where you probably spend more time than in your own crib – your office. Don’t be afraid to invest in high end contemporary office furniture. Remember, the work space deals with no cooking or kids playing. There are mature people using it, and for a very different purpose. The usage cannot be the same, even if employers tend to stroll around a lot and spill coffee all over. Therefore, it is safe to invest in furniture that looks and feels great.
    http://www.computer.cheapencorner.com

  10. Thanks for sharing your ideas in this article. The other thing is that if a problem arises with a laptop motherboard, folks should not consider the risk regarding repairing that themselves for if it is not done correctly it can lead to permanent damage to the entire laptop. It is usually safe to approach a dealer of the laptop for the repair of the motherboard. They’ve got technicians who may have an skills in dealing with notebook computer motherboard difficulties and can make the right diagnosis and undertake repairs.

  11. The things i have observed in terms of laptop memory is always that there are requirements such as SDRAM, DDR and the like, that must fit in with the specs of the motherboard. If the computer’s motherboard is very current and there are no computer OS issues, improving the memory space literally will take under sixty minutes. It’s one of many easiest computer system upgrade methods one can envision. Thanks for discussing your ideas.

  12. One thing I’d like to say is the fact before purchasing more laptop memory, check out the machine directly into which it would be installed. Should the machine is definitely running Windows XP, for instance, a memory limit is 3.25GB. The installation of greater than this would just constitute a new waste. Be sure that one’s motherboard can handle the particular upgrade volume, as well. Thanks for your blog post.

  13. The things i have observed in terms of personal computer memory is that often there are requirements such as SDRAM, DDR and so forth, that must fit the requirements of the mother board. If the computer’s motherboard is very current and there are no os issues, updating the storage space literally requires under an hour. It’s among the list of easiest laptop or computer upgrade types of procedures one can visualize. Thanks for giving your ideas.

  14. I have seen loads of useful things on your web site about pc’s. However, I’ve the viewpoint that notebook computers are still not nearly powerful sufficiently to be a sensible choice if you often do tasks that require plenty of power, like video modifying. But for world-wide-web surfing, microsoft word processing, and a lot other frequent computer work they are okay, provided you cannot mind the little screen size. Appreciate sharing your opinions.

  15. I’ve learned result-oriented things by means of your site. One other thing I’d like to say is always that newer computer system os’s have a tendency to allow additional memory to get used, but they as well demand more memory simply to operate. If one’s computer could not handle additional memory as well as newest software requires that memory space increase, it usually is the time to shop for a new Laptop. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *