asp.net MVC5 Add Verification (4) _ Practical Tips

Source: Internet
Author: User

Sometimes we need to add validation to our site, and in this section we demonstrate how to add validation using asp.net MVC5.

1. In the model class to add validation, the code is as follows:

 public class Movie
 {public
  int ID {get; set;}
  [Stringlength (60,minimumlength=3,errormessage= "Subject 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 ()]
  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 property, which sets the maximum string length, restricts the database, so the database structure changes. Let's take a look at the definition of what the database structure does not change.

2. Please look at the picture:

3. In the above picture, you see that all of the string types of fields are nvarchar (MAX), we will use the database migration technology to update the table structure, open the Package Manager console, and enter the following instructions:
Add-migration dataannotations
Update-database
When this instruction is finished, vs opens the generated migration file, in the up method you see the added database constraint:

4. Please look at the picture:

5. Next, we'll open the database to see what happens to the data table structure:

6.

This validation attribute specifies the attributes you want to apply to model. The required and Minimumlength properties indicate that you must have a value, but it does not prevent users from entering a space to satisfy this validation. The RegularExpression property, which is used to restrict what characters can be entered, in the above code genre and rating fields must be only letters, (spaces, numbers, and other special characters are not allowed.) , the Range property constrains a value that must be within a certain range, and the Stringlength property allows you to set the maximum length of the string, and the value type (for example, Decilmal,int float,datetime) is inherently needed, For required, however, it is not necessary.
Code first ensures that you specify the validation in model and can be validated before the database data is saved. For example, the following code, when SaveChanges calls, throws an error because there are some fields that must be missing.

Moviedbcontext db = new Moviedbcontext ();
 Movie Movie = new Movie ();
 Movie. Title = "Gone with the Wind";
 Db. Movies.add (movie);
 

7. Data validation, which is performed automatically through the. NET Framework, can make your program more robust, as it will ensure that you do not forget to verify some, and that it is not intentional to have bad data updated into the database.

8. Let's start with validation, run the project;

Click on this new link to add a new movie. Enter the illegal data and then see the error.

Support JQuery validation for non-english locales This use a comma (",") for a decimal point, you must include the NuGet Globalize as described previously in this tutorial.

9.

Note that the form automatically uses a red border to highlight the error data in the text box that you want to verify. The error message is displayed next to it. PS: Here I save time, just about to translate it, just the approximate meaning of the turn out. )
The real benefit is that you don't have to capture the validation rules that you wrote in the previous model class in order to be able to use the validation UI, and to change the code, controller, and view pages in the controller, or in the View page. Test validation, we use the Edit method, which also applies to the editing function.
The data for the form is not committed to the server unless there is no validation mechanism for the client error. You can press F12 in the browser and, in the Post method, set breakpoints to debug.

10. How does validation appear in views and methods:

What you might think of is how this interface is validated without having to modify the controller and view. The following code is the controller code that you created before, without any modifications to the

 Public ActionResult Create ()
 {return
   View ();
 }
 POST:/movies/create
 //To protect from overposting attacks, please enable the specific properties for you want to bind To, for 
 //More details, 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) shows the initial data, the second create method, and processing the form's submission. The second create method, which calls this modelstate.isvalid to check for data that is not validated in the movie entity. By calling Modelstate.isvalid, you can determine whether there are validation attributes that work on an object. If this object has a validation error, the Create method displays the form again, and if there are no errors, the data is saved to the database. In our example, when a client validation error occurs, the form's data is not committed to the server. This second create method is never invoked. If you disable the browser's JavaScript, the client's validation will fail, and then this post method of the Create method will call Modelstate.isvalid to check whether there is validation in the movie entity.

11. The code shown below is used to display an error message that displays a validation failure:

12. Read 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= "theme 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 ()] 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 property simply prompts the view engine to format the data. You can use the RegularExpression property to validate the formatted data, datatype is not a validation attribute, it is similar to the database, only specifies the data type, datatype enumerated types, and provides a number of data types, such as: Date,time, Phonenumber,currency,emailaddress and so on, the DataType property also guarantees that the program can create special types, such as a mailto:link can be used to create datatype.emailaddress ... DataType does not provide any validation.

Datatype.date cannot specify what format time to display. It is by default based on the time in the server.

[DisplayFormat (dataformatstring = "{0:yyyy-mm-dd}", Applyformatineditmode = True)]
Public DateTime enrollmentdate {get; set;}

14.

When in text-editing mode, the Applyformatineditmode attribute is applied. (You might not want this to be applied to a currency type field because you don't want the currency type to be in text-editing mode)
At this point, you can use DisplayFormat, but a better idea is to use datatype, which provides several benefits.
Browser support HTML5 Features
Browsers will display data correctly on your local computer by default

The DataType property ensures that MVC chooses the correct field, displays the data (DisplayFormat it is using a string template), and understands more. See ....
If you use the datatype attribute, you will have to specify the DisplayFormat attribute to ensure that the data is displayed correctly on Google browsers.
JQuery validation does not support the Range,datetime property, even if you specify a specific range, or you will report validation errors from the client

Look at the code:

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

The above is ASP.net MVC5 add verification method, hope to help everyone's study.

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.