Data verification and data verification code

Source: Internet
Author: User

Data verification and data verification code
Go back to the General Directory, "Step by Step Using the ABP framework to build a formal project series tutorial", verification Introduction

The input of an application must be verified first. This input can be user input or another application input. In a Web application, verification is usually performed twice: the first is client verification, and the second is server verification. Client-side verification is used to provide a better user experience. The fields in the detection form are used to remind users of required fields. server-side verification is more rigorous and unavoidable.

Server verification is implemented at the application service layer. The application service method should first check (verify) the input and then use it. ABC provides a good infrastructure to verify the input of application service methods.

The input service method uses a DTO object as the input parameter. An IValidate interface that can be implemented by DTO is provided to automatically verify these interfaces. Because IInputDto extends IValidate, input DTOs can only implement IInput to ensure verification.

Use Data Annotation

Data annotation is supported. The method for verifying the method is intercepted by the method parameter in the service layer through MethodInvocationValidator. The ValidationInterceptor is used to interceptor the method. The corresponding source code is in the namespace of "Abp. Runtime. Validation. Interception.

Now I add a class CreateCityInput TO THE CityInput file. The Code is as follows:

public class CreateCityInput : IInputDto, IShouldNormalize{    [Required]    public string Name { get; set; }    [Required]    public string Code { get; set; }    [Required]    public string ProvinceCode { get; set; }    public DateTime UpdatedTime { get; set; }    public string UpdatedBy { get; set; }    public void Normalize()    {        if (UpdatedTime==null)        {            UpdatedTime=DateTime.Now;        }    }}

The CreateCityInput class implements the IInput and IShouldNormalize interfaces, and is a required field in Name, Code, and ProvinceCode. Finally, it implements the Normalize method in the IShouldNormalize interface and determines whether UpdatedTime is null, if it is null, the value is assigned to the current time.

Add a method to the ICityAppService interface:

void CreateCity(CreateCityInput input);

This method is implemented in CityAppService:

Public void CreateCity (CreateCityInput input) {var city = _ cityRepository. FirstOrDefault (c => c. Name = input. Name); if (city! = Null) {throw new UserFriendlyException ("the city data already exists! ");} City = new Cities () {Code = input. Code, Name = input. Name, ProvinceCode = input. ProvinceCode}; _ cityRepository. Insert (city );}

Add the Create method to CityController:

Public ActionResult Create () {var input = new CreateCityInput () {Name = "WenZhou", ProvinceCode = "1", Code = "3" ,}; _ cityAppService. createCity (input); return Content ("OK ");}

Here, we create a CreateCityInput object, assign values to the three required fields, and then call the method of the service interface. if the service method is successfully executed, Return OK to the page.

Method execution is successful, and data is successfully added to the database.

Now we do not assign a value to one of the three required fields. Modify the CityController Code as follows:

Public ActionResult Create () {var input = new CreateCityInput () {Name = "Taizhou", // ProvinceCode = "1", Code = "3",}; _ cityAppService. createCity (input); return Content ("OK ");}

An error is returned. The error is "The method real parameter is invalid! Please refer to the verification error details ." It can be seen that errors caused by non-conforming attributes of the added data annotation are successfully intercepted. If the input value is null, an AbpValidationException is thrown. Therefore, you do not need to write code that detects null. If one of the input attributes is invalid, the same exception is thrown.

This mechanism is similar to ASP. net mvc verification mechanism, but note that the application service class is not derived from the Controller class. It is a common class and can work independently of the web.

Custom Verification

If the data annotation cannot meet your needs, you can also implementICustomValidate interface:

Public class CreateCityInput: IInputDto, IShouldNormalize, ICustomValidate {[Required] public string Name {get; set;} [Required] public string Code {get; set ;} [Required] public string ProvinceCode {get; set;} public DateTime UpdatedTime {get; set;} public string UpdatedBy {get; set;} public void Normalize () {if (UpdatedTime = null) {UpdatedTime = DateTime. now ;}} public void AddValidatio NErrors (List <ValidationResult> results) {if (ProvinceCode. Length> 5) {results. Add (new ValidationResult ("the province code Length cannot exceed 5 Characters! "));
Throw new Exception ("the province code length cannot exceed 5 Characters! ");}}}
Public ActionResult Create () {var input = new CreateCityInput () {Name = "Quzhou", ProvinceCode = "123456", Code = "4",}; _ cityAppService. createCity (input); return Content ("OK ");}

The code here is very simple and you don't need to explain it more. (If you have any questions, you can directly comment on the issue and test it.

 

Standardization

Standardization is to perform some additional operations after verification. In fact, the previous code has been standardized.

With the Normalize methodIShouldNormalize Interface. If this interface is implemented, the Normalize method is called after verification. As in the previous sample code:

public void Normalize(){    if (UpdatedTime==null)    {        UpdatedTime=DateTime.Now;    }}
After data verification, if the UpdatedTime attribute value is null, the current time is given to it. Of course, the data transmitted from the client may also be assigned an UpdatedTime value, so that the Normalize method will not be executed.

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.