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)]

6,949 thoughts on “MVC:对输入数据添加验证”

  1. One thing is always that one of the most frequent incentives for using your credit cards is a cash-back as well as rebate offer. Generally, you’re going to get 1-5% back for various buying. Depending on the credit cards, you may get 1% returning on most acquisitions, and 5% again on expenditures made on convenience stores, filling stations, grocery stores and also ‘member merchants’.

  2. Very good blog you have here but I was wanting to kmow if you new of any forums that cover
    the same topics discussed here? I’d really love
    to be a part of community where I can get responses from othher knowledgeable people that
    share thhe same interest. If you have any suggestions, please
    let me know. Bleszs you!

  3. Hey fantastic blog! Does runing a blog similar to this take a great deal of work?
    I’ve absolutely no understahding of computer programming however I was hopping to start
    my own blog in the nnear future. Anyway, should
    youu have any suggestions or tips for new blog owners please share.
    I know this is off subject but I imply had to ask.
    Cheers!

  4. Pingback: auto facebook post
  5. I have not checked in here for a while because I thought it was getting boring, but the last few posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  6. Heya i’m for the first time here. I came across this board and I to find It really helpful & it helped me out much. I’m hoping to provide something again and help others like you helped me.

  7. I am really inspired together with your writing
    talents as well as with the structure for your weblog. Is that this a paid theme or did you modify it yourself?
    Anyway stay up the nice high quality writing, it’s rare to peer a nice weblog like this one these days..

  8. Thanks for posting this awesome article. I’m a long time reader but I’ve never been compelled to leave a comment. I subscribed to your blog and shared this on my Facebook. Thanks again for a great post!

  9. Great blog post. Some tips i would like to bring up is that laptop or computer memory is required to be purchased should your computer still can’t cope with that which you do with it. One can put in two random access memory boards of 1GB each, in particular, but not one of 1GB and one with 2GB. One should always check the company’s documentation for one’s PC to make certain what type of storage is required.

  10. F*ckin’ remarkable issues here. I’m very glad to see your post. Thank you so much and i’m looking ahead to touch you. Will you please drop me a e-mail?

  11. I think this is among the most vital info for me. And i’m glad reading your
    article. But want to remark on some general things,
    The web site style is perfect, the articles is really great :
    D. Good job, cheers

  12. Thanks for the tips you have provided here. One more thing I would like to express is that personal computer memory requirements generally go up along with other advancements in the technological know-how. For instance, if new generations of cpus are brought to the market, there’s usually a related increase in the scale calls for of both laptop or computer memory plus hard drive space. This is because the software program operated by means of these processor chips will inevitably surge in power to make new know-how.

  13. Thank you for writing this awesome article. I’m a long time reader but I’ve never been compelled to leave a comment. I subscribed to your blog and shared this on my Facebook. Thanks again for a great post!

  14. Thanks for the guidelines you have provided here. Something important I would like to convey is that computer memory needs generally go up along with other advances in the technology. For instance, any time new generations of processor chips are made in the market, there is usually a corresponding increase in the size preferences of both personal computer memory in addition to hard drive space. This is because the application operated by means of these cpus will inevitably boost in power to benefit from the new technological innovation.

  15. Thanks for the guidelines you have provided here. Yet another thing I would like to convey is that computer memory requirements generally go up along with other developments in the technologies. For instance, any time new generations of processor chips are made in the market, there is usually a corresponding increase in the size and style preferences of both the personal computer memory plus hard drive space. This is because the application operated by way of these processors will inevitably boost in power to benefit from the new technology.

Leave a Reply

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