vapor-docs/build/1.5/guide/validation.html

533 lines
24 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vapor Documentation</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Quicksand:400,700,300">
<link rel="stylesheet" href="/1.5/styles/vapor-code.css">
<link rel="stylesheet" href="/1.5/styles/main.css">
</head>
<body>
<header>
<a class="logo" href="/1.5/">
<img src="/1.5/images/droplet.svg" alt="Vapor">
<h1>Vapor <em>Docs</em></h1>
</a>
<ul>
<li>
<a href="http://vapor.codes">Home</a>
</li>
<li>
<a href="http://example.vapor.codes">Example</a>
</li>
<li>
<a href="https://github.com/vapor/vapor">GitHub</a>
</li>
<li>
<a href="https://twitter.com/@codevapor">Twitter</a>
</li>
<li>
<a href="http://vapor.team">Slack</a>
</li>
</ul>
</header>
<nav>
<a href="#" class="toggle show"></a>
<a href="#" class="toggle close">&times;</a>
<div class="scroll">
<section>
<h3>Getting Started</h3>
<ul>
<li class="">
<a href="/1.5/getting-started/install-swift-3-macos.html">
Install Swift 3: macOS
</a>
</li>
<li class="">
<a href="/1.5/getting-started/install-swift-3-ubuntu.html">
Install Swift 3: Ubuntu
</a>
</li>
<li class="">
<a href="/1.5/getting-started/install-toolbox.html">
Install Toolbox
</a>
</li>
<li class="">
<a href="/1.5/getting-started/hello-world.html">
Hello, World
</a>
</li>
<li class="">
<a href="/1.5/getting-started/manual.html">
Manual
</a>
</li>
<li class="">
<a href="/1.5/getting-started/xcode.html">
Xcode
</a>
</li>
</ul>
</section>
<section>
<h3>Guide</h3>
<ul>
<li class="">
<a href="/1.5/guide/droplet.html">
Droplet
</a>
</li>
<li class="">
<a href="/1.5/guide/folder-structure.html">
Folder Structure
</a>
</li>
<li class="">
<a href="/1.5/guide/json.html">
JSON
</a>
</li>
<li class="">
<a href="/1.5/guide/config.html">
Config
</a>
</li>
<li class="">
<a href="/1.5/guide/views.html">
Views
</a>
</li>
<li class="">
<a href="/1.5/guide/leaf.html">
Leaf
</a>
</li>
<li class="">
<a href="/1.5/guide/controllers.html">
Controllers
</a>
</li>
<li class="">
<a href="/1.5/guide/middleware.html">
Middleware
</a>
</li>
<li class="active">
<a href="/1.5/guide/validation.html">
Validation
</a>
</li>
<li class="">
<a href="/1.5/guide/provider.html">
Provider
</a>
</li>
<li class="">
<a href="/1.5/guide/sessions.html">
Sessions
</a>
</li>
<li class="">
<a href="/1.5/guide/hash.html">
Hash
</a>
</li>
<li class="">
<a href="/1.5/guide/commands.html">
Commands
</a>
</li>
</ul>
</section>
<section>
<h3>Routing</h3>
<ul>
<li class="">
<a href="/1.5/routing/basic.html">
Basic
</a>
</li>
<li class="">
<a href="/1.5/routing/parameters.html">
Route Parameters
</a>
</li>
<li class="">
<a href="/1.5/routing/query-parameters.html">
Query Parameters
</a>
</li>
<li class="">
<a href="/1.5/routing/group.html">
Group
</a>
</li>
<li class="">
<a href="/1.5/routing/collection.html">
Collection
</a>
</li>
</ul>
</section>
<section>
<h3>Fluent</h3>
<ul>
<li class="">
<a href="/1.5/fluent/driver.html">
Driver
</a>
</li>
<li class="">
<a href="/1.5/fluent/model.html">
Model
</a>
</li>
<li class="">
<a href="/1.5/fluent/query.html">
Query
</a>
</li>
<li class="">
<a href="/1.5/fluent/relation.html">
Relation
</a>
</li>
</ul>
</section>
<section>
<h3>Auth</h3>
<ul>
<li class="">
<a href="/1.5/auth/user.html">
User
</a>
</li>
<li class="">
<a href="/1.5/auth/middleware.html">
Middleware
</a>
</li>
<li class="">
<a href="/1.5/auth/request.html">
Request
</a>
</li>
<li class="">
<a href="/1.5/auth/protect.html">
Protect
</a>
</li>
</ul>
</section>
<section>
<h3>HTTP</h3>
<ul>
<li class="">
<a href="/1.5/http/request.html">
Request
</a>
</li>
<li class="">
<a href="/1.5/http/response.html">
Response
</a>
</li>
<li class="">
<a href="/1.5/http/body.html">
Body
</a>
</li>
<li class="">
<a href="/1.5/http/response-representable.html">
ResponseRepresentable
</a>
</li>
<li class="">
<a href="/1.5/http/responder.html">
Responder
</a>
</li>
<li class="">
<a href="/1.5/http/client.html">
Client
</a>
</li>
<li class="">
<a href="/1.5/http/server.html">
Server
</a>
</li>
<li class="">
<a href="/1.5/http/cors.html">
CORS
</a>
</li>
</ul>
</section>
<section>
<h3>WebSockets</h3>
<ul>
<li class="">
<a href="/1.5/websockets/droplet.html">
Droplet
</a>
</li>
<li class="">
<a href="/1.5/websockets/custom.html">
Custom
</a>
</li>
</ul>
</section>
<section>
<h3>Testing</h3>
<ul>
<li class="">
<a href="/1.5/testing/modules.html">
Modules
</a>
</li>
<li class="">
<a href="/1.5/testing/basic.html">
Basic
</a>
</li>
</ul>
</section>
<section>
<h3>Deploy</h3>
<ul>
<li class="">
<a href="/1.5/deploy/nginx.html">
Nginx
</a>
</li>
<li class="">
<a href="/1.5/deploy/supervisor.html">
Supervisor
</a>
</li>
</ul>
</section>
<section>
<h3>Version (1.5)</h3>
<ul>
<li class="">
<a href="/1.5/switch/1_5.html">
1.5
</a>
</li>
<li class="">
<a href="/1.5/switch/2_0.html">
2.0
</a>
</li>
</ul>
</section>
</div>
</nav>
<main>
<a href="https://github.com/vapor/documentation/blob/master/CONTRIBUTING.md" class="edit">✎ Edit on GitHub</a>
<h1 id="validation">Validation</h1>
<p>Vapor provides a few different ways to validate data coming into your application. Let's start by looking at the most common.</p>
<h2 id="common-usage">Common Usage</h2>
<p>Several useful convenience validators are included by default. You can use these to validate data coming into your application, or combine them and create your own.</p>
<p>Let's look at the most common way to validate data.</p>
<pre><code class="language-swift">class Employee {
var email: Valid&lt;Email&gt;
var name: Valid&lt;Name&gt;
init(request: Request) throws {
name = try request.data["name"].validated()
email = try request.data["email"].validated()
}
}</code></pre>
<p>Here we have a typical Employee model with an <code>email</code> and <code>name</code> property. By declaring both of these properties as <code>Valid&lt;&gt;</code>, you are ensuring that these properties can only ever contain valid data. The Swift type checking system will prevent anything that does not pass validation from being stored.</p>
<p>To store something in a <code>Valid&lt;&gt;</code> property, you must use the <code>.validated()</code> method. This is available for any data returned by <code>request.data</code>.</p>
<p><code>Email</code> is a real <code>validator</code> included with Vapor, but <code>Name</code> is not. Let's take a look at how you can create a Validator.</p>
<pre><code class="language-swift">Valid&lt;OnlyAlphanumeric&gt;
Valid&lt;Email&gt;
Valid&lt;Unique&lt;T&gt;&gt;
Valid&lt;Matches&lt;T&gt;&gt;
Valid&lt;In&lt;T&gt;&gt;
Valid&lt;Contains&lt;T&gt;&gt;
Valid&lt;Count&lt;T&gt;&gt;</code></pre>
<h2 id="validators-vs-validationsuites">Validators vs. ValidationSuites</h2>
<p>Validators, like <code>Count</code> or <code>Contains</code> can have multiple configurations. For example:</p>
<pre><code class="language-swift">let name: Valid&lt;Count&lt;String&gt;&gt; = try "Vapor".validated(by: Count.max(5))</code></pre>
<p>Here we are validating that the <code>String</code> is at most 5 characters long. The type of <code>Valid&lt;Count&gt;</code> tells us that the string has been validated to be a certain count, but it does not tell us exactly what that count was. The string could have been validated to be less than three characters or more than one million.</p>
<p>Because of this, <code>Validators</code> themselves are not as type safe as some applications might desire. <code>ValidationSuites</code> fix this. They combine multiple <code>Validators</code> and/or <code>ValidationSuites</code> together to represent exactly what type of data should be considered valid.</p>
<h2 id="custom-validator">Custom Validator</h2>
<p>Here is how to create a custom <code>ValidationSuite</code>.</p>
<pre><code class="language-swift">class Name: ValidationSuite {
static func validate(input value: String) throws {
let evaluation = OnlyAlphanumeric.self
&amp;&amp; Count.min(5)
&amp;&amp; Count.max(20)
try evaluation.validate(input: value)
}
}</code></pre>
<p>You only have to implement one method. In this method, use any other validators or logic to create your custom validator. Here we are defining a <code>Name</code> as only accepting alphanumeric Strings that are between 5 and 20 characters.</p>
<p>Now we can be sure that anything of type <code>Valid&lt;Name&gt;</code> follows these rules.</p>
<h2 id="combining-validators">Combining Validators</h2>
<p>In the <code>Name</code> validator, you can see that <code>&amp;&amp;</code> is being used to combine validators. You can use <code>&amp;&amp;</code> as well as <code>||</code> to combine any validator as you would boolean values with an <code>if</code> statement.</p>
<p>You can also use <code>!</code> to invert the validator.</p>
<pre><code class="language-swift">let symbols = input.validated(by: !OnlyAlphanumeric.self)</code></pre>
<h2 id="testing-validity">Testing Validity</h2>
<p>While <code>validated() throw</code> is the most common method for validating, there are two others.</p>
<pre><code class="language-swift">let passed = input.passes(Count.min(5))
let valid = try input.tested(Count.min(5))</code></pre>
<p><code>passes()</code> returns a boolean indicating whether or not the test passed. <code>tested()</code> will throw if the validation does not pass. But unlike <code>validated()</code> which returns a <code>Valid&lt;&gt;</code> type, <code>tested()</code> returns the original type of the item it was called on.</p>
<h2 id="validation-failures">Validation Failures</h2>
<p>Vapor will automatically catch validation failures in the <code>ValidationMiddleware</code>. But you can catch them on your own, or customize responses for certain types of failures.</p>
<pre><code class="language-swift">do {
//validation here
} catch let error as ValidationErrorProtocol {
print(error.message)
}</code></pre>
</main>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/1.5/scripts/highlight.pack.js"></script>
<script>
hljs.registerLanguage("leaf", function (hljs) {
/* Author: Hale Chan <halechan@qq.com> */
return {
c: [
{
cN: 'function',
b: '#+',
e: '[)] ',
rB: true,
eE: false,
c : [
{
b: '[(]',
e: '[)]',
eE: true,
c: [
{
cN: 'string',
b: '"',
e: '"'
},
{
cN: 'title',
b: '[A-Za-z_][A-Za-z_0-9]*'
}
]
},
{
cN: 'keyword',
b: '#+([A-Za-z$_][0-9A-Za-z$_]*)?',
eP: true
},
]
}
]
};
});
</script>
<script>
$(function() {
// Syntax highlighting
hljs.initHighlightingOnLoad();
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
$('body').addClass('safari');
}
$('h1, h2, h3, h4, h5, h6').each(function(key, item) {
var $item = $(item);
var id = $item.attr('id');
if (id) {
var link = $('<a>');
link.attr('href', '#' + id);
$item.wrap(link);
}
})
$('a.toggle').on('click', function(e){
e.preventDefault();
console.log('hi');
var body = $('body');
if (body.hasClass('toggled')) {
body.removeClass('toggled');
} else {
body.addClass('toggled');
}
})
var lastScroll = 0;
var isUp = false;
var win = $(window);
win.on('scroll', function(){
var scrollTop = win.scrollTop();
var scrollBottom = win.scrollTop() + win.height();
var docHeight = $(document).height();
if ( scrollTop < 0 || scrollBottom >= docHeight ){
return;
}
if (scrollTop > (lastScroll + 0) && scrollTop >= 0) {
if (!isUp) {
$('a.toggle.show').addClass('hide')
}
isUp = true;
lastScroll = scrollTop;
} else if (scrollTop < (lastScroll - 0)) {
if (isUp) {
$('a.toggle.show').removeClass('hide')
}
isUp = false;
lastScroll = scrollTop;
}
});
// scroll to the active nav item
$("nav .scroll").animate({
scrollTop: $("nav .active").offset().top - 157
}, 0);
// var lastScrollTop = 0;
// $(window).scroll(function(event){
// var st = $(this).scrollTop();
// if (st > lastScrollTop){
// $('a.toggle.show').addClass('hide')
// } else {
// $('a.toggle.show').removeClass('hide')
// }
// lastScrollTop = st;
// });
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-76177358-4', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>