Detailed explanation of background verification before asp.net full stack development tutorial

Time:2019-10-31

Preface

In the development of web system, there are often a large number of interactive operations. Interaction must verify the accuracy of data, not to mention that a field may have multiple verifications. If a form is submitted with 10 fields, do we need to write code to verify these 10 fields separately? If so, isn’t it too painful to write a verification for each form?

In order to solve this problem, smart programmers began to “lazy”!

Today, we introduce a lazy “fluent validation” on the. Net platform. As its name implies, fluent validation makes our validation development work fluent or even beautiful.

Let’s see how to use it.

First we use nuget to install fluent validation

Nuget install command:Install-Package FluentValidation -Version 7.6.104

Since the validation of fluent validation is model-based, let’s build a person first

public class Person
 {
  /// <summary>
  // / name
  /// </summary>
  public string Name { get; set; }
  /// <summary>
  // / age
  /// </summary>
  public int Age { get; set; }
  /// <summary>
  // / sex
  /// </summary>
  public bool Sex { get; set; }

 }

With the model, to verify the model, there must be a verifier, so we are creating a person verifier.

public class PersonValidator : AbstractValidator<Person>
 {
  public PersonValidator()
  {
   this.RuleFor(p => p.Name)
    .NotEmpty()
    . withmessage ("name cannot be empty");
   this.RuleFor(p => p.Age)
    .NotEmpty()
    . withmessage ("age cannot be empty!!");
  }
 }

Verifier must inherit fromAbstractValidator<T>, the generic T represents the entity verified by the verifier, and passes thethis.RuleForSet validation for the specified property. In the above configuration, set non null for the name and age properties of person, and give the corresponding error message.

Now that we have the entity and the verifier, we are far from it.

class Program
 {
  static void Main(string[] args)
  {
   Server(new Person { });

   Console.ReadKey(true);
  }

  private static void Server(Person model)
  {
   var validator = new PersonValidator();

   ValidationResult result = validator.Validate(model);
   if (!result.IsValid)
   {
    foreach (var failure in result.Errors)
    {
     //Failed property name, such as error message
     Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
    }
   }
   Console. Writeline ("validation complete!");
  }
 }

A parameter person is required in the server method. Person is an object with three properties name, age and sex. In the server, we create a person verifier object to verify our parameter model. After verification, a verification result will be returned. There are two important parameters for this result. The first is isvalid, which returns true when the validation passes. The second is errors, which stores all the information about the validation failure. When the validation fails, you can get all the error information by traversing the errors. As shown above, you can know which object is wrong by the propertyname of the error information, and the ErrorMessage will naturally. There is a withmessage corresponding to the wrong content of this property. Here are the results

 

At this point, we are able to use basic validation.

However, in our practical application, it may not be as smooth as the above case. Maybe our person will have an address attribute, whose type is not a string, but an object address, as shown below.

public class Person
 {
  /// <summary>
  // / name
  /// </summary>
  public string Name { get; set; }
  /// <summary>
  // / age
  /// </summary>
  public int Age { get; set; }
  /// <summary>
  // / sex
  /// </summary>
  public bool Sex { get; set; }

  /// <summary>
  // / address
  /// </summary>
  public Address Address { get; set; }
 }
public class Address
 {
  /// <summary>
  ///Home address
  /// </summary>
  public string Home { get; set; }

  /// <summary>
  ///Home phone
  /// </summary>
  public string Phone { get; set; }
 }

If address also has a verifier

public class AddressValidator : AbstractValidator<Address>
 {
  public AddressValidator()
  {
   this.RuleFor(m => m.Home)
    .NotEmpty()
    . withmessage ("home address cannot be empty");

   this.RuleFor(m => m.Phone)
    .Length(11, 12)
    . withmessage ("phone number must be between 11 and 12 digits");
  }
 }

Now the requirements have changed. In the person entity requirements, not only the name and age cannot be empty, but also the home and phone under the address must meet the requirements of the addressvalidator. What can I do?

Of course you can do it like this

public class PersonValidator : AbstractValidator<Person>
 {
  public PersonValidator()
  {
   this.RuleFor(p => p.Name)
     .NotEmpty()
     . withmessage ("name cannot be empty");
   this.RuleFor(p => p.Age)
    .NotEmpty()
    . withmessage ("age cannot be empty!!");

   this.RuleFor(p => p.Address.Home)
    .MinimumLength(5)
    . withmessage ("minimum length of home address is 5")

  }
 }

It’s not impossible to configure verification for each attribute through person.address, but if there are many address attributes, the workload will be greatly increased when they are configured, and someone else’s addressvalidator has finished the configuration. Do you want to configure it again, which is a waste of life?

Fortunately, fluent validation provides a mechanism for setting validators for properties.

public class PersonValidator : AbstractValidator<Person>
 {
  public PersonValidator()
  {
   this.RuleFor(p => p.Name)
     .NotEmpty()
     . withmessage ("name cannot be empty");
   this.RuleFor(p => p.Age)
    .NotEmpty()
    . withmessage ("age cannot be empty!!");

   this.RuleFor(p => p.Address)
    .NotNull()
    . withmessage ("address cannot be empty")
    .SetValidator(new AddressValidator());

  }
 }

In this way, we append the verification of home and phome under address to the address property of person.

This is the first place to know and use it. Thank you very much. It will be updated continuously until the system architecture is built.

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.