ASP. NET MVC5 add verification (4), asp. netmvc5

Source: Internet
Author: User

ASP. NET MVC5 add verification (4), asp. netmvc5

Sometimes we need to add verification to our website. This section demonstrates how to use ASP. NET MVC5 to add verification.

1. Add verification in the Model class. The Code is as follows:

Public class Movie {public int ID {get; set;} [StringLength (60, MinimumLength = 3, ErrorMessage = "the topic length must be 3 to 60 characters")] 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] * $")] public string Rating {get; set ;}}

This StringLength attribute sets the maximum String Length and limits the database, so the database structure will change. Let's take a look at the definition before the database structure is changed.

2. See the figure below:

3. in the above image, you can see that all string fields are NVARCHAR (MAX). We will use the database migration technology to update the table structure and open the Package Manager Console, enter the following command:
Add-migration DataAnnotations
Update-database
After this command is completed, VS opens the generated migration file. In the Up method, you can see the added database constraints:

4. See the image:

5. Next, let's open the database to see what changes have taken place in the data table structure:

6.

This verification attribute specifies the attribute you want to apply to the Model. The Required and MinimumLength attributes indicate that there must be a value, but do not prevent users from entering a space to perform this verification. RegularExpression attribute, used to restrict the characters that can be entered. In the above Code, the Genre and Rating fields must be only letters (spaces, numbers and other special characters are not allowed .), The Range attribute limits a value to be within a specific Range. The StringLength attribute allows you to set the maximum length and Value Type of a string (for example, decilmal, int float, DateTime) they are all internal needs, but they are not Required for Required.
Code First makes sure that you specify the verification in the Model, which can be verified before the database data is saved. For example, in the following code, when SaveChanges is called, an error is thrown because some required fields are lost.

MovieDBContext db = new MovieDBContext(); Movie movie = new Movie(); movie.Title = "Gone with the Wind"; db.Movies.Add(movie); db.SaveChanges(); // <= Will throw server side validation exception 

7. data verification, passed. NET Framework is automatically executed, which can make your program more robust. Similarly, it will ensure that you will not forget to verify some, or intentionally updating bad data to the database.

8. Now let's verify and run the project;

Click the new link to add a new movie. Enter invalid data and an error is displayed.

Note to support jQuery validation for non-English locales that use a comma (",") for a decimal point, you must include the NuGet globalize as described previously in this tutorial.

9.

Note: The form automatically uses a red border to highlight the error data in the text box to be verified. The error message is displayed. (PS: I will save some time here, and I will translate it at will, just to translate it out .)
The real benefit is that you do not have to change the code, Controller, and view page in the Controller or view page to use the validation UI, the verification rules you wrote in the previous Model class are captured. For test verification, we use the editing method, which also applies to the editing function.
Form data is not submitted to the server unless there is no authentication mechanism for client errors. You can press F12 in the browser and set the breakpoint for debugging in the Post method.

10. How does the verification appear in the view and method:

You may think about how the interface validation is generated without modifying the controller and view. The following code is the Controller code. The code you created earlier has not been modified.

 public ActionResult Create() {   return View(); } // POST: /Movies/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for  // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie) {   if (ModelState.IsValid)   {     db.Movies.Add(movie);     db.SaveChanges();     return RedirectToAction("Index");   }   return View(movie); }

The first Create method (http get) displays the initial data. The second Create method processes the submission of the form. The second create method calls this ModelState. IsValid to check whether there is any data in the movie object that fails verification. You can call ModelState. IsValid to determine whether a validation attribute exists. It is used on an object. If this object has a verification error, the Create method will display the form again. If there is no error, the data will be saved to the database. In our example, when an error occurs during client verification, the form data is not submitted to the server. The second Create method will never be called. If you disable javascript in the browser, the client verification will fail. Then, the Post-created Create method will call ModelState. IsValid to check whether the Movie entity has failed verification.

11. The code shown below is used to display the error message displayed when verification fails:

12. Check the Code directly:

Using System; using System. collections. generic; using System. linq; using System. web; using System. data. entity; using System. componentModel. dataAnnotations; namespace MvcMovie. models {public class Movie {public int ID {get; set;} [StringLength (60, MinimumLength = 3, ErrorMessage = "the topic length must be 3 to 60 characters")] 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] * $")] public string Rating {get; set ;}} public class MovieDBContext: DbContext {public DbSet <Movie> Movies {get; set ;}}}

13.

The DataType attribute only prompts the view engine to format the data. You can use the RegularExpression attribute to verify the formatted data. DataType is not a validation attribute. It is similar to the database but only specifies the data type. DataType Enumeration type provides many data types, such: date, Time, PhoneNumber, Currency, EmailAddress, etc. The DataType attribute also ensures that the program can create some special types. For example, a mailto: link can be used to create DataType. emailAddress... DataType does not provide any verification.

DataType. Date cannot specify the formatting time. It is based on the time on the server by default.

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]public DateTime EnrollmentDate { get; set; }

14.

In text editing mode, the ApplyFormatInEditMode attribute is applied. (You may not want to apply this situation to fields of the currency type, because you do not want the currency type to be in text editing mode)
At this time, you can use DisplayFormat, but a better idea is to use DataType, which provides several benefits.
HTML5 features supported by browsers
The browser displays data correctly on your local computer by default.

The DataType attribute ensures that the correct field is selected by MVC and data is displayed (DisplayFormat uses a string template). For more information, see ....
If you use the DataType attribute, You have to specify the DisplayFormat attribute to ensure that the data can be correctly displayed on Google Chrome.
JQuery validation does not support the Range and DateTime attributes. Even if you specify a specific Range, the client verification error is returned.

Check the Code:

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

The above is the method for adding authentication to ASP. NET MVC5. I hope it will be helpful for your learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.