In the previous article, the user’s registration and login functions are introduced. When registering users, the format of user name and password can be limited in the form of code. If it does not meet the requirements, the operation cannot be completed, as shown in the following figure:
The principle of this function is the error information given by the entity framework component based on identity after verifying the data submitted by users before adding users.
Data verification function is very necessary in every software system. In order to avoid system errors caused by invalid or illegal data input by users, it is necessary to verify the data before processing or persistence to ensure the correctness and validity of the data.
● input verification
●. Net verification introduction
● back end model validation of asp.net MVC
● client model validation of asp.net MVC
● client verification of asp.net MVC
● model validation in custom asp.net MVC
The purpose of input validation is to determine whether a variable can meet the specified requirements. Now that we have mentioned“judge”The most direct way to use a program is to use judgment statements, such as:
But is there a unified way to verify data in. Net? Otherwise, each time through the judgment statement to write verification code can not be reused and affect reading.
Validation of. Net
In. Net, a feature-based data type tagging and validation mechanism is provided.
1. Tags for data types:
. net has a class library called system. Componentmodel. Dataannotations, which contains many attributes. These attributes are used to tag data type information for attributes in. Net types. For example, data length, format, whether it can be empty, etc.
The following figure shows some types in this class library, from which you can see such feature types as credit card, email address, maximum / minimum length, etc
There are three types of data annotation attributes:
● validation feature: used to execute validation rules, such as mailbox address, data type, data length, number interval, regular expression and other validation features.
● presentation feature: used to specify how the tagged type or attribute is displayed on the UI.
● model relationship feature: used to specify the relationship between class members and other types, such as foreign key features.
The following figure is the result of marking the name attribute of an entity type through its properties. From the name of the tag, it can be easily seen that the name attribute is required and the maximum length is 30. The name displayed is “name”.
But it should be noted that system.componentmodel.dataannotations providesFeature is just a descriptionBecause you limit the length of a string, it will not be able to assign a string that exceeds the limit,It must call the validation method manually or use it in asp.net MVC, EF。 (refer to: https://stackoverflow.com/questions/6496705/how-do-data-annotations-work)
For the feature types provided by dataannotations, please refer to: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
2. Validation of data types
After the type is marked with data attribute tag, special verification type is needed to complete the verification. This type also exists in the system.componentmodel.dataannotations assembly named validator. The following figure is the definition of validator. From its description, this class is used to verify the types, attributes and methods of the validationattribute attribute tag:
3. Type validation example
Use a console program to demonstrate how to use data validation in. Net:
First create a console program and add a reference to the system.componentmodel.dataannotations assembly, then write the following code:
After running, the following error messages will be output:
After adding display properties:
Optimized verification prompt information:
4. Custom authentication method:
The built-in data validation features of the system are all inherited to the validationattribute type. Next, you can implement your own data validation method by inheriting this type:
First, add a type that inherits validationattribute and override its isvalid method, which contains the logic of data validation and sets the corresponding error information:
Then apply the property on the corresponding class attribute:
Please refer to https://msdn.microsoft.com/en-us/library/cc668224.aspx for the custom authentication feature
Model validation of asp.net MVC
ASP.NET MVC provides the function of model validation based on feature tags. As long as the corresponding data validation feature is added to the type attribute used as the action parameter, ASP.NET MVC will perform model bindingAutomatic verification of marked properties。 The result of the validation is represented by the isvalid property of the modelstate in the controller.
Here’s how to add data validation to the model in asp.net MVC:
1. Mark with the attribute of model, such as required, password type and comparison between attributes, etc
2. Add modelstate.isvalid judgment in the action code. When an error occurs, carry the error information to the view through the addmodelerror method of the modelstate object:
3. Use the html.validationsummary method in view to output validation information:
Note: if there is code for client verification in view, you need to comment out @ scripts. Render (“~ / bundles / jqueryval”) first. This file is used for client verification, which will be described later.
4. Using HTML object on the page to generate corresponding HTML tags according to the model
5. Run program
Enter a blank user name and two mismatched passwords, and click submit:
Show validation failed:
Output on page:
6. Use the display feature to optimize the output of attribute names:
Client model validation of asp.net MVC
The model validation of asp.net MVC server is introduced earlier. When the data is submitted to the server, the validation method can filter the invalid data requests before the business logic, but the requests still need to be sent to the server. When there are too many requests, these invalid requests will occupy a lot of server resources, so if the corresponding validation can be completed at the client , so the response speed is improved for the customer, and the pressure is reduced for the server. Asp.net MVC combines with jQuery validation plug-in to provide the browser side data validation function.
1. Add the following code to introduce the validation related JS code:
2. Use the forXXX method of the HTML object to generate the HTML code of the corresponding tag of the model on the view:
3. Operation effect:
The result is consistent with the server-side verification, but when you click the registration button, you no longer send the post request to the server, but the data verification completed in the browser through JS code.
About jQuery validation of asp.net MVC client
JQuery validation is a plug-in of jQuery, which provides powerful form data validation function. It can simply and quickly add some common data validation for web applications, such as required, number, email, phone number, regular expression and other common format validation. Its validation function is completed by adding some properties or setting their types in the form label, as shown in the following figure. The code comes from the official document, which provides the validation of length limit, required, email format and URL format:
For more information about jQuery validation, please refer to the document: https://jquery validation.org/documentation/
Asp.net MVC is to mark the corresponding tags by inserting data Val * and other attributes on the tags in HTML, and then the introduced JS completes the specific functions by reading these special tags. The following is to generate HTML through html.textboxfor method:
It can be seen from the code that in addition to the normal attributes of the input tag, related attributes with the prefix of data Val are generated, which will be used to assist JS code to complete data validation.
About @ scripts. Render (“~ / bundles / jqueryval”):
First, the script object’s render method is used to add the specified script file path to the page, and its parameter is an array of strings representing the path of the script file.
So which file does ~ / bundles / jQuery Val point to?
Then register it to a global static bundle list just like register route:
In this way, you can use ~ / bundles / jQuery Val on the UI to get the JS files related to validation. More about UI will be introduced in the following articles.
Model validation in custom asp.net MVC
The above describes the model validation in asp.net MVC, which has built-in some commonly used validation methods, but in the actual development, there will still be situations that can not meet the needs, so in these cases, we need to define validation according to the actual needs, including back-end validation and front-end validation.
1. Add custom validation properties:
The above code needs to pay attention to the following points:
● implements validationattribute type andRewroteFor getting error informationFormatererrormessage methodAnd theIsvalid method。
● RealizedUnder the system.web.mvc namespaceIclientvalidatable interface, which is an interface extended by asp.net MVC to realize client-side verification. The interface is used to create and return a list of verification rules. The verification rules mainly include three attributes: error information, verification type, and verification parameter. The error information adds “from client-side verification” in the default information to distinguish server-side verification.
Note: since client validation is only a feature of asp.net MVC, the iclientvalidatable interface exists in the system.web.mvc assembly.
2. Expand the jQuery validation plug-in, add a validation extension file named myblog.validate.extension.js, and add a new validation method to jQuery validation（Note: the first parameter of the method is consistent with the validationtype property set in the getclientvalidationrules method）, finally, add the association between MVC and jQuery validation through jquery.validator.unobtrusive.adapters:
Note: when adding association code, you need to add messages and rules with the same name as validationtype property.
3. Introduce the expanded JS file into the page:
4. Apply the newly added attribute to the corresponding type attribute:
5. Execution result:
Data validation is a very important function for applications. From the analysis of this paper, it can be seen that a data may be validated when the client enters, when the server receives and when the business logic is processed. Then there may be questions about whether these codes are repeated and unnecessary. The answer is No. first of all, for the server, all the data from the client The data on the client side is untrustworthy, so whether the data has been verified in the browser or not, it needs to be verified on the server side. For the business logic, it is a whole, which itself defines what data is legal and what is illegal, so it must contain the verification logic itself, otherwise the unit test of the business logic cannot pass, As the receiver of the request, the model validation of the server decides whether to execute the corresponding business logic, which is independent and related.
There is no magic in asp.net. The verification method of asp.net MVC model is the whole content shared by the editor. I hope to give you a reference, and I hope you can support developer more.