ASP. NET web API tutorial (5) data verification

Source: Internet
Author: User

How can I use Web APIs to ensure data validity? In actual projects, no data is submitted to meet the requirements. Besides, there are more than N keywords in tianchao. Therefore, the following content adds web API data verification.
Step 1 modify the Object Model Public Class Userinfo
{
Public Int Id { Get ; Set ;}
[Required]
[Stringlength ( 20 , Errormessage = " The name is too long or too short. " , Minimumlength = 4 )]
Public String Name { Get ;Set ;}

[Regularexpression ( @" ([2-5] \ D) " , Errormessage = " Between 20 and 50 " )]
Public Int Age {Get ; Set ;}
}

Note: You need to add system. componentmodel. dataannotations; reference

Step 2 Add filter

Public Class Validationattribute: actionfilterattribute
{
Public Override Void Onactionexecuting (httpactioncontext actioncontext)
{
If (! Actioncontext. modelstate. isvalid)
{
Actioncontext. Response = actioncontext. Request. createerrorresponse (
Httpstatuscode. badrequest,
Actioncontext. modelstate );
}
}
}

Note: The namespace must be introduced.

Using System. Web;
Using System. Web. http. filters;
Using System. Web. http. modelbinding;
Using System. Web. http. controllers;
Using System. net. HTTP;
Using System. net;
Using Newtonsoft. JSON. LINQ;

 

Step 3 register the filter
Open webapiconfig
AddCode

Config. Filters. Add ( New Filters. validationattribute ());

 

Step 4: Compile the page
Introduce JS/CSS

< Link Href = "Content/site.css" REL = "Stylesheet" Type = "Text/CSS"   />
< Script SRC = "Scripts/jquery-1.7.1.min.js" Type = "Text/JavaScript" > </ Script >
< Script SRC = "Scripts/knockout-2.1.0.js" Type = "Text/JavaScript" > </ Script >
< Script SRC = "Scripts/jquery. Validate. Min. js" Type = "Text/JavaScript" > </ Script >
< Script SRC = "Scripts/jquery. Validate. unobtrusive. Min. js" Type = "Text/JavaScript" > </ Script >

 

Copy htmlpage2 content for slight modification

< Label For = "Text" >
Name </ Label >
< Input ID = "Name" Name = "Name" Data-Val = "True" Data-Val-required = "Did you forget to enter the name? " Type = "Text"
Value = ""   />
< Span Class = "Field-Validation-valid" Data-valmsg- = "Name" Data-valmsg-replace = "True" >
</ Span >
< Label For = "Text" >
Age </ Label >
< Input ID = "Age" Name = "Age" Type = "Text" Data-Val = "True" Data-Val-required = "Age is also required! "
Value = ""   />
< Span Class = "Field-Validation-valid" Data-valmsg- = "Age" Data-valmsg-replace = "True" >
</ Span >
< BR />
< Button Type = "Submit" >
Submit </ Button >

 

Add js to display the error message returned by the Service.

$. Validator. addmethod ("failure", function () {return false ;});
$. Validator. unobtrusive. adapters. addbool ("failure ");
$. Validator. unobtrusive. revalidate = function (Form, validationresult ){
$. Removedata (Form [0], 'validator ');
VaR servervalidationerrors = [];
For (VAR property in validationresult ){
VaR elementid = property. tolowercase ();
Elementid = elementid. substr (elementid. indexof ('.') + 1 );
VaR item = form. Find ('#' + elementid );
Servervalidationerrors. Push (item );
Item. ATTR ('data-Val-failure ', validationresult [property] [0]);
Jquery. validator. unobtrusive. parseelement (item [0]);
}
Form. Valid ();
$. Removedata (Form [0], 'validator ');
$. Each (servervalidationerrors, function (){
This. removeattr ('data-Val-failure ');
Jquery. validator. unobtrusive. parseelement (this [0]);
});
}

 

Added the server error message display operation

400/* badrequest */: function (jqxhr ){
VaR validationresult = $. parsejson (jqxhr. responsetext );
$. Validator. unobtrusive. revalidate (Form, validationresult. modelstate );
}

View test results
1. No input
 

 

2 The input is invalid.

Complete code:/files/risk/web API 5/mvcapplication1.rar

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.