Home Backend Development PHP Tutorial Share MVC data validation example introduction

Share MVC data validation example introduction

Jun 15, 2017 pm 01:48 PM
mvc data verification

This article mainly introduces the relevant information of MVC data verification in detail, which has certain reference value. Interested friends can refer to it

1. General situation

For those who have used the MVC framework, the data verification of MVC will be familiar. For example, I have a Model as follows:


##

public class UserInfo
  {
    [Required(ErrorMessage = "UserName不可为空1111")]
    public string UserName { get; set; }
    public string Sex { get; set; }
    public string Mobile { get; set; }
    public string Address { get; set; }
  }
Copy after login

Front end :


@using (Html.BeginForm()) 
{
  @Html.AntiForgeryToken()
  <p class="form-horizontal">
    <h4>UserInfo</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <p class="form-group">
      @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      <p class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
      </p>
    </p>
  </p>
}
Copy after login

Effect:

Yes, MVC can be added by adding some

attributes Certain characteristics are used to verify the data. This may not be unfamiliar to everyone.

If that’s all it is, then there’s nothing wrong with it.

2. Common situations

In actual development, we mostly use EF or other methods to make every table or

view in the database , all correspond to a class in the code Model, we should not modify the model generated through the database, to say the least, even if we add some data verification features to some attributes in this class , then, after the database changes, if I regenerate these Models, the verification features we added before will be gone. So, how do we solve this problem?

If:


public class UserInfo
  {  
    public string UserName { get; set; }
    public string Sex { get; set; }
    public string Mobile { get; set; }
    public string Address { get; set; }
  }
Copy after login

UserInfo is a model generated through the database. We should not modify the model generated by the database. But that is, we need to perform data verification on certain attributes in this model. For example, we need to perform non-null verification on the UserName attribute. So how do we do it?

Everyone usually thinks of partial classification. Yes, we can solve the above problems through partial classification.

First, we add the keyword partial to the class in the model, and then we write a partial class of this model.


public partial class UserInfo
  {
    [Required(ErrorMessage = "UserName不可为空1111")]
    public string UserName { get; set; }
  }
Copy after login

However, this will prompt us with an error, that is, there are duplicate attributes in the class. Yes, in some classes, attributes cannot have the same name. So, what should we do? The MVC framework has already given us a solution.

We can write like this:


[MetadataType(typeof(MeteUserInfo))]
  public partial class UserInfo
  {
    private class MeteUserInfo
    {
      [Required(ErrorMessage = "UserName不可为空1111")]
      public string UserName { get; set; }
    }
  }
Copy after login

In this way, our above problems will be easily solved.

The above is the detailed content of Share MVC data validation example introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a drop-down list with symbols in Excel How to create a drop-down list with symbols in Excel Apr 14, 2023 am 09:04 AM

Creating a drop-down list in an Excel worksheet is easy, as long as it's a regular drop-down menu. But what if you have to make it special by adding a special symbol, or make it even more special by adding some text as well as symbols? Ok, sounds interesting but wondering if this is possible? What's an answer you don't know when Geek Page is here to help? This article is all about creating dropdown menus with symbols as well as symbols and text. Hope you enjoyed reading this article! Also Read: How to Add Dropdown Menu in Microsoft Excel Part 1: Create a Dropdown List with Only Symbols To create a dropdown menu with symbols, we first need to create the source

PHP MVC Architecture: Building Web Applications for the Future PHP MVC Architecture: Building Web Applications for the Future Mar 03, 2024 am 09:01 AM

Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

Example of new features in PHP8: How to use type declarations and code to strengthen data validation? Example of new features in PHP8: How to use type declarations and code to strengthen data validation? Sep 12, 2023 pm 01:21 PM

Example of new features in PHP8: How to use type declarations and code to strengthen data validation? Introduction: With the release of PHP8, developers have welcomed a series of new features and improvements. One of the most exciting is the ability for type declarations and code to enforce data validation. This article will take some practical examples to introduce how to use these new features to strengthen data validation and improve code readability and maintainability. Advantages of type declaration: Before PHP7, the type of variables could be changed at will, which brought great difficulties to data verification.

An advanced guide to PHP MVC architecture: unlocking advanced features An advanced guide to PHP MVC architecture: unlocking advanced features Mar 03, 2024 am 09:23 AM

The MVC architecture (Model-View-Controller) is one of the most popular patterns in PHP development because it provides a clear structure for organizing code and simplifying the development of WEB applications. While basic MVC principles are sufficient for most web applications, it has some limitations for applications that need to handle complex data or implement advanced functionality. Separating the model layer Separating the model layer is a common technique in advanced MVC architecture. It involves breaking down a model class into smaller subclasses, each focusing on a specific functionality. For example, for an e-commerce application, you might break down the main model class into an order model, a product model, and a customer model. This separation helps improve code maintainability and reusability. Use dependency injection

How to use excel data validation-How to use excel data validation How to use excel data validation-How to use excel data validation Mar 04, 2024 pm 12:25 PM

Do you know how to use excel data verification? Below, the editor will bring you how to use excel data verification. I hope it will be helpful to everyone. Let’s learn with the editor! 1. First, in the EXCEL table, select the required Set the cell for the drop-down option, as shown in the figure below: 2. Then click [Data] on the menu bar, as shown in the figure below: 3. After opening the data menu, you will see the [Data Validation] option, click [Data] After verification], continue to click [Data Verification] in the open options to open the data verification window for settings, as shown in the figure below: The above is the entire content of how to use excel data verification brought by the editor. I hope it will be helpful to you. Everyone can help.

How to perform data reliability verification and model evaluation in Python How to perform data reliability verification and model evaluation in Python Oct 20, 2023 pm 04:06 PM

How to perform data reliability verification and model evaluation in Python Data reliability verification and model evaluation are very important steps when working with machine learning and data science models. This article will introduce how to use Python for data reliability verification and model evaluation, and provide specific code examples. Data Reliability Validation Data reliability validation refers to the verification of the data used to determine its quality and reliability. The following are some commonly used data available

How to deal with data inconsistency errors between the development environment and the production environment in PHP language development? How to deal with data inconsistency errors between the development environment and the production environment in PHP language development? Jun 10, 2023 am 10:31 AM

With the rapid development of the Internet, developers' tasks have also become diverse and complex. Especially for PHP language developers, one of the most common problems faced during the development process is the error of data inconsistency between the development environment and the production environment. Therefore, how to handle these errors is an important issue that developers must face when developing PHP applications. The difference between development environment and production environment The first thing to make clear is that development environment and production environment are different, and they have different settings and configurations. in development environment

ThinkPHP6 form validation and data validation: ensuring the legality of data ThinkPHP6 form validation and data validation: ensuring the legality of data Aug 26, 2023 pm 01:55 PM

ThinkPHP6 form validation and data validation: ensuring the legality of data. In the process of web application development, form validation is an important part of ensuring the legality and integrity of data. The ThinkPHP6 framework provides powerful form validation and data validation functions, which can simplify the development process and help us reduce the occurrence of errors and vulnerabilities. 1. Form validation validation rule declaration ThinkPHP6 supports the use of annotations to declare validation rules for the controller's request method. We can do this on the request method of the controller

See all articles