Laravel 中可用的验证规则
Laravel 将始终检查会话数据中的错误,并自动将它们绑定到视图(如果可用)。因此,重要的是要注意$errors变量将始终在每个请求的所有视图中可用,使您可以方便地假设$errors变量总是被定义并且可以安全地使用。下表显示了 Laravel 中所有可用的验证规则。
Laravel 中可用的验证规则 |
Accepted |
Active URL |
After (Date) |
Alpha |
Alpha Dash |
Alpha Numeric |
Array |
Before (Date) |
Between |
Boolean |
Confirmed |
Date |
Date Format |
Different |
Digits |
Digits Between |
E-Mail |
Exists (Database) |
Image (File) |
In |
Integer |
IP Address |
JSON |
Max |
MIME Types(File) |
Min |
Not In |
Numeric |
Regular Expression |
Required |
Required If |
Required Unless |
Required With |
Required With All |
Required Without |
Required Without All |
Same |
Size |
String |
Timezone |
Unique (Database) |
URL |
这$errors变量将是一个实例Illuminate\Support\MessageBag。通过添加如下代码可以在视图文件中显示错误消息。
@if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
例子
步骤 1− 创建一个名为ValidationController通过执行以下命令。
php artisan make:controller ValidationController --plain
步骤 2− 成功执行后,您将收到以下输出 −
步骤 3- 将以下代码复制到
app/Http/Controllers/ValidationController.php文件。
app/Http/Controllers/ValidationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ValidationController extends Controller {
public function showform() {
return view('login');
}
public function validateform(Request $request) {
print_r($request->all());
$this->validate($request,[
'username'=>'required|max:8',
'password'=>'required'
]);
}
}
步骤 4- 创建一个名为的视图文件resources/views/login.blade.php并将以下代码复制到该文件中。
resources/views/login.blade.php
<html>
<head>
<title>Login Form</title>
</head>
<body>
@if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<?php
echo Form::open(array('url'=>'/validation'));
?>
<table border = '1'>
<tr>
<td align = 'center' colspan = '2'>Login</td>
</tr>
<tr>
<td>Username</td>
<td><?php echo Form::text('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo Form::password('password'); ?></td>
</tr>
<tr>
<td align = 'center' colspan = '2'
><?php echo Form::submit('Login'); ? ></td>
</tr>
</table>
<?php
echo Form::close();
?>
</body>
</html>
步骤 5- 添加以下行app/Http/routes.php.
app/Http/routes.php
Route::get('/validation','ValidationController@showform');
Route::post('/validation','ValidationController@validateform');
步骤 6− 访问以下 URL 来测试验证。
http://localhost:8000/validation
步骤 7− 单击“Login”按钮,无需在文本字段中输入任何内容。输出将如下图所示。