1679674096
在本文中,我们将看到如何在 laravel 10 中验证 ajax 表单。这里我们将学习 laravel 10 ajax 表单验证示例。简单地说,我们将创建一个引导程序模式。在此模式中,我们将创建一个包含基本输入的表单。提交表单后,我们将在不刷新页面的情况下检查验证。
当我们需要在没有页面刷新的情况下提交带有验证的表单时,您可以使用本教程。在此示例中,我们将使用 ajax 调用提交表单并在 laravel 10 中验证表单。
那么,让我们看看 laravel 10 ajax 表单验证示例、带验证的 laravel 10 ajax 表单提交、laravel 10 ajax 表单提交以及如何使用 jquery 验证 ajax 表单。
第一步:安装 Laravel 10
在此步骤中,我们将使用以下命令安装 laravel 10。
composer create-project laravel/laravel laravel_10_ajax_form_validation
第 2 步:创建迁移和模型
现在,我们将使用以下命令创建模型和迁移。
php artisan make:migration create_users_table
移民:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
之后,我们将使用以下命令将表迁移到数据库。
php artisan migrate
现在,我们将使用以下命令创建一个用户模型。
应用程序/模型/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
第三步:创建控制器
在此步骤中,我们将使用以下命令创建一个 UserController文件。
php artisan make:controller UserController
应用程序/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('index', compact('users'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
], [
'name.required' => 'Name field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.',
]);
$user = User::create($validatedData);
return response()->json(['success' => 'User created successfully.']);
}
}
第 4 步:添加路线
现在,我们将向web.php文件添加路由。
路线/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(UserController::class)->group(function(){
Route::get('index', 'index');
Route::post('store', 'store')->name('store');
});
第 5 步:创建刀片文件
在这一步中,我们将创建一个 index.blade.php 文件。因此,将以下代码添加到该文件中。
资源/视图/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 AJAX Form Validation Example - Websolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
<strong>Laravel 10 AJAX Form Validation Example - Websolutionstuff</strong>
</div>
<div class="card-body">
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#userModal">
Create User
</button>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="ajax-form" action="{{ route('store') }}">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
<div class="mb-3 text-center">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$('#ajax-form').submit(function(e) {
e.preventDefault();
var url = $(this).attr("action");
let formData = new FormData(this);
$.ajax({
type:'POST',
url: url,
data: formData,
contentType: false,
processData: false,
success: (response) => {
alert('Form submitted successfully');
location.reload();
},
error: function(response){
$('#ajax-form').find(".print-error-msg").find("ul").html('');
$('#ajax-form').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
第 6 步:运行 Laravel 10 应用程序
现在,我们将使用以下命令运行带有验证的 laravel 10 ajax 表单提交。
php artisan serve
输出:
原文出处:https: //websolutionstuff.com/
1679667060
В этой статье мы увидим, как проверить форму ajax в laravel 10. Здесь мы узнаем о примере проверки формы ajax laravel 10. Просто мы создадим модальное окно начальной загрузки. В этом модальном окне мы создадим форму с основными входными данными. при отправке формы мы проверим валидацию без обновления страницы.
Когда нам нужно требовать отправки формы без обновления страницы с проверкой, вы можете использовать этот учебник. В этом примере, используя вызов ajax, мы отправим форму и проверим форму в laravel 10.
Итак, давайте посмотрим пример проверки формы laravel 10 ajax, отправку формы laravel 10 ajax с проверкой, отправку формы laravel 10 ajax и как проверить форму ajax с помощью jquery.
Шаг 1: Установите Laravel 10
На этом этапе мы установим laravel 10, используя следующую команду.
composer create-project laravel/laravel laravel_10_ajax_form_validation
Шаг 2: Создайте миграцию и модель
Теперь мы создадим модель и миграцию, используя следующую команду.
php artisan make:migration create_users_table
Миграция:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
После этого мы перенесем таблицу в базу данных с помощью следующей команды.
php artisan migrate
Теперь мы создадим модель пользователя, используя следующую команду.
приложение/Модели/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Шаг 3: Создайте контроллер
На этом шаге мы создадим файл UserController , используя следующую команду.
php artisan make:controller UserController
приложение/Http/Контроллеры/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('index', compact('users'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
], [
'name.required' => 'Name field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.',
]);
$user = User::create($validatedData);
return response()->json(['success' => 'User created successfully.']);
}
}
Шаг 4: Добавьте маршруты
Теперь мы добавим маршруты в файл web.php .
маршруты/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(UserController::class)->group(function(){
Route::get('index', 'index');
Route::post('store', 'store')->name('store');
});
Шаг 5: Создайте файл блейда
На этом шаге мы создадим файл index.blade.php . Итак, добавьте следующий код в этот файл.
ресурсы/представления/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 AJAX Form Validation Example - Websolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
<strong>Laravel 10 AJAX Form Validation Example - Websolutionstuff</strong>
</div>
<div class="card-body">
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#userModal">
Create User
</button>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="ajax-form" action="{{ route('store') }}">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
<div class="mb-3 text-center">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$('#ajax-form').submit(function(e) {
e.preventDefault();
var url = $(this).attr("action");
let formData = new FormData(this);
$.ajax({
type:'POST',
url: url,
data: formData,
contentType: false,
processData: false,
success: (response) => {
alert('Form submitted successfully');
location.reload();
},
error: function(response){
$('#ajax-form').find(".print-error-msg").find("ul").html('');
$('#ajax-form').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
Шаг 6: Запустите приложение Laravel 10
Теперь мы запустим отправку формы ajax laravel 10 с проверкой, используя следующую команду.
php artisan serve
Выход:
Оригинальный источник статьи: https://websolutionstuff.com/
1679648760
In this article, we will see how to validate the ajax form in laravel 10. Here we will learn about the laravel 10 ajax form validation example. Simply we will create a bootstrap modal. In this modal, we will create a form with basic inputs. when the form is submitted we will check validation without page refresh.
When we need to require without page refresh form submits with validation you can use this tutorial. In this example, using ajax call we will submit the form and validate the form in laravel 10.
So, let's see the laravel 10 ajax form validation example, laravel 10 ajax form submit with validation, laravel 10 ajax form submit, and how to validate the ajax form using jquery.
Step 1: Install Laravel 10
In this step, we will install laravel 10 using the following command.
composer create-project laravel/laravel laravel_10_ajax_form_validation
Step 2: Create Migration and Model
Now, we will create a model and migration using the following command.
php artisan make:migration create_users_table
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
After that, we will migrate the table to the database using the following command.
php artisan migrate
Now, we will create a User model using the following command.
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step 3: Create Controller
In this step, we will create a UserController file using the following command.
php artisan make:controller UserController
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::get();
return view('index', compact('users'));
}
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
], [
'name.required' => 'Name field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.',
]);
$user = User::create($validatedData);
return response()->json(['success' => 'User created successfully.']);
}
}
Step 4: Add Routes
Now, we will add routes to the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(UserController::class)->group(function(){
Route::get('index', 'index');
Route::post('store', 'store')->name('store');
});
Step 5: Create Blade File
In this step, we will create an index.blade.php file. So, add the following code to that file.
resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 AJAX Form Validation Example - Websolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
<strong>Laravel 10 AJAX Form Validation Example - Websolutionstuff</strong>
</div>
<div class="card-body">
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#userModal">
Create User
</button>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="ajax-form" action="{{ route('store') }}">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
<div class="mb-3 text-center">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$('#ajax-form').submit(function(e) {
e.preventDefault();
var url = $(this).attr("action");
let formData = new FormData(this);
$.ajax({
type:'POST',
url: url,
data: formData,
contentType: false,
processData: false,
success: (response) => {
alert('Form submitted successfully');
location.reload();
},
error: function(response){
$('#ajax-form').find(".print-error-msg").find("ul").html('');
$('#ajax-form').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
Step 6: Run Laravel 10 Application
Now, we will run laravel 10 ajax form submit with validation using the following command.
php artisan serve
Output:
Original article source at: https://websolutionstuff.com/
1679584020
В этой статье мы увидим пример проверки формы laravel 10. Здесь мы узнаем об основном вводе формы с проверкой laravel. Laravel предлагает несколько разных подходов к проверке входящих данных вашего приложения.
Для любых входящих данных нам необходимо проверить их перед сохранением в базе данных. Чаще всего используется validate метод, доступный для всех входящих HTTP-запросов.
Итак, давайте посмотрим, как проверить форму в laravel 10, проверку формы в laravel 10, проверку laravel 10, пользовательскую проверку в laravel 10 и пользовательское сообщение проверки laravel.
Шаг 1: Установите Laravel 10
На этом этапе мы установим приложение laravel 10, используя следующую команду.
composer create-project laravel/laravel laravel_10_form_validation
Шаг 2: Добавьте маршрут
На этом этапе мы добавим маршруты в файл web.php .
маршруты/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('index', [ UserController::class, 'index' ]);
Route::post('store', [ UserController::class, 'store' ])->name('store');
Шаг 3: Создайте пользовательский контроллер
Теперь мы создадим UserController, используя следующую команду.
php artisan make:controller UserController
приложение/Http/Контроллеры/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index(){
return view('index');
}
public function store(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'password' => 'required|min:5',
'confirm_password' => 'required|same:password|min:5',
'email' => 'required|email|unique:users'
], [
'name.required' => 'Name field is required.',
'password.required' => 'Password field is required.',
'confirm_password.required' => 'Confirm password field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
$user = User::create($validatedData);
return back()->with('success', 'User created successfully.');
}
}
В laravel 10 в качестве альтернативы правила проверки могут быть указаны как массивы правил вместо одной | строки с разделителями.
$validatedData = $request->validate([
'name' => 'required',
'password' => ['required', 'min:8'],
'email' => ['required, email, unique:users'],
]);
Остановка при первой неудачной проверке
Иногда нам нужно прекратить выполнение правил проверки для атрибута после первой неудачной проверки. Для этого назначьте bail правило атрибуту в laravel 10.
$request->validate([
'name' => 'bail|required|unique:users|max:255',
'password' => ['required', 'min:8'],
'email' => ['bail, required, email, unique:users'],
]);
В этом примере, если уникальное правило для атрибута имени не выполняется, максимальное правило не проверяется. Правила будут проверяться в порядке их назначения.
Шаг 4: Добавьте файл блейда
На этом шаге мы создадим файл index.blade.php .
ресурсы/представления/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Form Validation Example - Websolutionstuff</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-md-6">
<h3 class="mt-5">Laravel 10 Form Validation Example - Websolutionstuff</h3>
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<!-- Way 1: Display All Error Messages -->
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="POST" action="{{ route('store') }}">
{{ csrf_field() }}
<div class="mb-3">
<label class="form-label" for="inputName">Name:</label>
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" placeholder="Name">
<!-- Way 2: Display Error Message -->
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="mb-3">
<label class="form-label" for="inputEmail">Email:</label>
<input type="text" name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email">
@error('email')
<span class="text-danger">{{ $message }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Password:</label>
<input type="password" name="password" class="form-control @error('password') is-invalid @enderror" placeholder="Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Confirm Password:</label>
<input type="password" name="confirm_password" class="form-control @error('confirm_password') is-invalid @enderror" placeholder="Confirm Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('confirm_password'))
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
@endif
</div>
<div class="mb-3">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
Оригинальный источник статьи: https://websolutionstuff.com/
1679580204
在本文中,我们将看到 laravel 10 表单验证示例。在这里,我们将学习使用 laravel 验证的基本表单输入。Laravel 提供了几种不同的方法来验证应用程序的传入数据。
对于任何传入的数据,我们需要在将其存储到数据库之前对其进行验证。最常见的方法是 validate 对所有传入的 HTTP 请求使用可用的方法。
那么,让我们看看如何在 laravel 10 中验证表单、在 laravel 10 中验证表单、在 laravel 10 中验证、在 laravel 10 中自定义验证以及自定义 laravel 验证消息。
第一步:安装 Laravel 10
在此步骤中,我们将使用以下命令安装 laravel 10 应用程序。
composer create-project laravel/laravel laravel_10_form_validation
第 2 步:添加路线
在此步骤中,我们将向 web.php 文件添加路由。
路线/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('index', [ UserController::class, 'index' ]);
Route::post('store', [ UserController::class, 'store' ])->name('store');
第三步:创建用户控制器
现在,我们将使用以下命令创建 UserController。
php artisan make:controller UserController
应用程序/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index(){
return view('index');
}
public function store(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'password' => 'required|min:5',
'confirm_password' => 'required|same:password|min:5',
'email' => 'required|email|unique:users'
], [
'name.required' => 'Name field is required.',
'password.required' => 'Password field is required.',
'confirm_password.required' => 'Confirm password field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
$user = User::create($validatedData);
return back()->with('success', 'User created successfully.');
}
}
在 laravel 10 中,验证规则可以指定为规则数组而不是单个 | 分隔字符串。
$validatedData = $request->validate([
'name' => 'required',
'password' => ['required', 'min:8'],
'email' => ['required, email, unique:users'],
]);
在第一次验证失败时停止
有时我们需要在第一次验证失败后停止对属性运行验证规则。为此,请将 bail 规则分配给 laravel 10 中的属性。
$request->validate([
'name' => 'bail|required|unique:users|max:255',
'password' => ['required', 'min:8'],
'email' => ['bail, required, email, unique:users'],
]);
在此示例中,如果 name属性 上的 唯一规则 失败, 则不会检查max规则。规则将按照分配的顺序进行验证。
第 4 步:添加刀片文件
在这一步中,我们将创建一个 index.blade.php文件。
资源/视图/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Form Validation Example - Websolutionstuff</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-md-6">
<h3 class="mt-5">Laravel 10 Form Validation Example - Websolutionstuff</h3>
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<!-- Way 1: Display All Error Messages -->
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="POST" action="{{ route('store') }}">
{{ csrf_field() }}
<div class="mb-3">
<label class="form-label" for="inputName">Name:</label>
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" placeholder="Name">
<!-- Way 2: Display Error Message -->
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="mb-3">
<label class="form-label" for="inputEmail">Email:</label>
<input type="text" name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email">
@error('email')
<span class="text-danger">{{ $message }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Password:</label>
<input type="password" name="password" class="form-control @error('password') is-invalid @enderror" placeholder="Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Confirm Password:</label>
<input type="password" name="confirm_password" class="form-control @error('confirm_password') is-invalid @enderror" placeholder="Confirm Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('confirm_password'))
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
@endif
</div>
<div class="mb-3">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
原文出处:https: //websolutionstuff.com/
1679565600
In this article, we will see the laravel 10 form validation example. Here, we will learn about basic form input with laravel validation. Laravel provides several different approaches to validate your application's incoming data.
For any incoming data, we need to validate it before storing it in the database. It is most common to use the validate
method available on all incoming HTTP requests.
So, let's see how to validate a form in laravel 10, form validation in laravel 10, laravel 10 validation, custom validation in laravel 10, and custom laravel validation message.
Step 1: Install Laravel 10
In this step, we will install the laravel 10 application using the following command.
composer create-project laravel/laravel laravel_10_form_validation
Step 2: Add Route
In this step, we will add routes to the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('index', [ UserController::class, 'index' ]);
Route::post('store', [ UserController::class, 'store' ])->name('store');
Step 3: Create UserController
Now, we will create UserController using the following command.
php artisan make:controller UserController
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index(){
return view('index');
}
public function store(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'password' => 'required|min:5',
'confirm_password' => 'required|same:password|min:5',
'email' => 'required|email|unique:users'
], [
'name.required' => 'Name field is required.',
'password.required' => 'Password field is required.',
'confirm_password.required' => 'Confirm password field is required.',
'email.required' => 'Email field is required.',
'email.email' => 'Email field must be email address.'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
$user = User::create($validatedData);
return back()->with('success', 'User created successfully.');
}
}
In laravel 10 Alternatively, validation rules may be specified as arrays of rules instead of a single |
delimited string.
$validatedData = $request->validate([
'name' => 'required',
'password' => ['required', 'min:8'],
'email' => ['required, email, unique:users'],
]);
Stopping On First Validation Failure
Sometimes we need to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail
rule to the attribute in laravel 10.
$request->validate([
'name' => 'bail|required|unique:users|max:255',
'password' => ['required', 'min:8'],
'email' => ['bail, required, email, unique:users'],
]);
In this example, if the unique rule on the name attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.
Step 4: Add Blade File
In this step, we will create an index.blade.php file.
resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Form Validation Example - Websolutionstuff</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-md-6">
<h3 class="mt-5">Laravel 10 Form Validation Example - Websolutionstuff</h3>
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<!-- Way 1: Display All Error Messages -->
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="POST" action="{{ route('store') }}">
{{ csrf_field() }}
<div class="mb-3">
<label class="form-label" for="inputName">Name:</label>
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" placeholder="Name">
<!-- Way 2: Display Error Message -->
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="mb-3">
<label class="form-label" for="inputEmail">Email:</label>
<input type="text" name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email">
@error('email')
<span class="text-danger">{{ $message }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Password:</label>
<input type="password" name="password" class="form-control @error('password') is-invalid @enderror" placeholder="Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Confirm Password:</label>
<input type="password" name="confirm_password" class="form-control @error('confirm_password') is-invalid @enderror" placeholder="Confirm Password">
<!-- Way 3: Display Error Message -->
@if ($errors->has('confirm_password'))
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
@endif
</div>
<div class="mb-3">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
Original article source at: https://websolutionstuff.com/
1678879080
Felte is a simple to use form library for Svelte, Solid and React. No Field
or Form
components are needed, just plain stores and actions to build your form however you like. You can see it in action in this CodeSandbox demo!
name
attribute is necessary).reporter
packages.<script>
import { createForm } from 'felte';
const { form } = createForm({
onSubmit: async (values) => {
/* call to an api */
},
});
</script>
<form use:form>
<input type="text" name="email" />
<input type="password" name="password" />
<button type="submit">Sign In</button>
</form>
import { createForm } from '@felte/solid';
function Form() {
const { form } = createForm({
onSubmit: async (values) => {
/* call to an api */
},
});
return (
<form use:form>
<input type="text" name="email" />
<input type="password" name="password" />
<button type="submit">Sign In</button>
</form>
);
}
import { useForm } from '@felte/react';
// if using preact, use `@felte/preact`
function Form() {
const { form } = useForm({
onSubmit: async (values) => {
/* call to an api */
},
});
return (
<form ref={form}>
<input type="text" name="email" />
<input type="password" name="password" />
<button type="submit">Sign In</button>
</form>
);
}
<script type="module">
import 'https://unpkg.com/@felte/element@0.4.0/dist/min/felte-form.js';
const felteForm = document.querySelector('felte-form');
felteForm.configuration = {
onSubmit: async (values) => {
console.log(values);
},
};
</script>
<felte-form>
<form>
<input type="text" name="email" />
<input type="password" name="password" />
<button type="submit">Sign In</button>
</form>
</felte-form>
This example works without a bundler! Copy its contents to an HTML file and open it on your browser. A more complete example like this, with validation and error reporting, can be found here.
You can find fully functional examples on the /examples directory of this repository. You should be able to open them on CodeSandbox by replacing github's url to githubbox
. E.g. Replace https://github.com/pablo-abc/felte/tree/main/examples/svelte/basic
with https://githubbox.com/pablo-abc/felte/tree/main/examples/svelte/basic
.
This repository is a mono-repo containing multiple packages located in the packages
directory. Maintained using pnpm and Changesets.
We provide two packages that are specific to Svelte:
This is the core package that contains all the basic functionality you need to handle your forms in Svelte. Felte optionally allows you to use error reporters (see them as plugins) to prevent you from needing to find a way to display your errors on your form manually. For this we provide already some reporter packages contained in this same repo.
A reporter package that uses a Svelte component to pass the validation messages for you to display. This provides an API that might feel the most familiar to most developers.
We provide two packages that are specific to Solid:
This is the core package that contains all the basic functionality you need to handle your forms in Solid. Same as felte
but specifically made for Solid.
A reporter package that uses a Solid component to pass the validation messages for you to display. This provides an API that might feel the most familiar to most developers.
We provide two packages that are specific to React:
This is the main package that contains the basic functionality you need to handle your forms in React. Same as felte
but specifically made for React.
A reporter packages that uses a React component to pass the validation messages for you to display. This provides an API that might feel the most familiar to most developers.
We provide two packages that are specific to Preact:
This is the main package that contains the basic functionality you need to handle your forms in Preact. Same as felte
but specifically made for Preact. The API is the same as @felte/react
so you can refer to the same documentation.
A reporter packages that uses a Preact component to pass the validation messages for you to display. This provides an API that might feel the most familiar to most developers. The API is the same as @felte/react
so you can refer to the same documentation.
We provide three packages that can be used with only VanillaJS. Two of them using Web Components. These elements do not use the shadow DOM since there is no reason to isolate styles.
This is the main package that contains the basic functionality you need to handle your forms in vanilla JS using a custom element. Similar to felte
but specifically made to be used as a custom element. This is the recommended way to handle your forms when using Vanilla JS. Web components are well supported by all major browsers so this should be a safe option unless you need to support legacy browsers.
A reporter packages that uses a custom element to display validation messages on the DOM. This the recommended way to display your validation messages when using vanilla JS.
This is the main package that contains the basic functionality you need to handle your forms in vanilla JS. Similar to felte
and other integrations but with all code related to frameworks removed. This requires a bit more work to use, since you'll be the one in charge of cleaning up subscribers and listeners on it. It's API is basically the same as felte
(Svelte's integration) so you can use Svelte's documentation as a reference. This can be used as a starting point to create your own integration/package for other environments. When it comes to vanilla JS we'd recommend using @felte/element
using web components.
The following packages can be used with any of the framework specific felte
wrappers:
A utility package to help you validate your form with Yup.
A utility package to help you validate your form with Zod.
A utility package to help you validate your form with Superstruct.
A utility package to help you validate your form with Vest.
The following packages can be used with any of the framework specific felte
wrappers:
A reporter that uses Tippy.js to display your validation messages without needing any extra work.
A reporter that uses the browser's constraint validation API to display your validation messages.
A reporter that displays the error messages in the DOM, either as a single element or a list of elements.
If you want to contribute to this project you may check CONTRIBUTING.md
for general guidelines on how to do so.
While further testing would be needed to provide an accurate answer, Felte should work in all evergreen browsers. Polyfills might be needed if you target older browsers such as IE 11 for, at least, Promise.all
, Element.closest
, URLSearchParams
, fetch
, CustomEvent
and iterators.
Author: pablo-abc
Source Code: https://github.com/pablo-abc/felte
License: MIT license
1674813120
In this article, we will see how to validate multi step form wizard using jquery. Here, we will learn to validate the multi step form using jquery. First, we create the multi step form using bootstrap. Also, in this example, we are not using any jquery plugin for multi step form wizard.
So, let's see jquery multi step form with validation, how to create multi step form, multi step form wizard with jquery validation, bootstrap 4 multi step form wizard with validation, multi step form bootstrap 5, and jQuery multi step form with validation and next previous navigation.
Add HTML:
<html lang="en">
</head>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
</head>
<body>
<div class="main">
<h3>How To Validate Multi Step Form Using jQuery - Websolutionstuff</h3>
<form id="multistep_form">
<!-- progressbar -->
<ul id="progress_header">
<li class="active"></li>
<li></li>
<li></li>
</ul>
<!-- Step 01 -->
<div class="multistep-box">
<div class="title-box">
<h2>Create your account</h2>
</div>
<p>
<input type="text" name="email" placeholder="Email" id="email">
<span id="error-email"></span>
</p>
<p>
<input type="password" name="pass" placeholder="Password" id="pass">
<span id="error-pass"></span>
</p>
<p>
<input type="password" name="cpass" placeholder="Confirm Password" id="cpass">
<span id="error-cpass"></span>
</p>
<p class="nxt-prev-button"><input type="button" name="next" class="fs_next_btn action-button" value="Next" /></p>
</div>
<!-- Step 02 -->
<div class="multistep-box">
<div class="title-box">
<h2>Social Profiles</h2>
</div>
<p>
<input type="text" name="twitter" placeholder="Twitter" id="twitter">
<span id="error-twitter"></span>
</p>
<p>
<input type="text" name="facebook" placeholder="Facebook" id="facebook">
<span id="error-facebook"></span>
</p>
<p>
<input type="text" name="linkedin" placeholder="Linkedin" id="linkedin">
<span id="error-linkedin"></span>
</p>
<p class="nxt-prev-button">
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" class="ss_next_btn action-button" value="Next" />
</p>
</div>
<!-- Step 03 -->
<div class="multistep-box">
<div class="title-box">
<h2>Personal Details</h2>
</div>
<p>
<input type="text" name="fname" placeholder="First Name" id="fname">
<span id="error-fname"></span>
</p>
<p>
<input type="text" name="lname" placeholder="Last Name" id="lname">
<span id="error-lname"></span>
</p>
<p>
<input type="text" name="phone" placeholder="Phone" id="phone">
<span id="error-phone"></span>
</p>
<p>
<textarea name="address" placeholder="Address" id="address"></textarea>
<span id="error-address"></span>
</p>
<p class="nxt-prev-button"><input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit_btn ts_next_btn action-button" value="Submit" />
</p>
</div>
</form>
<h1>You are successfully logged in</h1>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.0/jquery.easing.js" type="text/javascript"></script>
</body>
</html>
Add CSS:
body {
display: inline-block;
width: 100%;
height: 100vh;
overflow: hidden;
background-image: url("https://img1.akspic.com/image/80377-gadget-numeric_keypad-input_device-electronic_device-space_bar-3840x2160.jpg");
background-repeat: no-repeat;
background-size: cover;
position: relative;
margin: 0;
font-weight: 400;
font-family: 'Roboto', sans-serif;
}
body:before {
content: "";
display: block;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.main {
position: absolute;
left: 0;
right: 0;
top: 30px;
margin: 0 auto;
height: 515px;
}
input:-internal-autofill-selected {
background-color: #fff !important;
}
#multistep_form {
width: 550px;
margin: 0 auto;
text-align: center;
position: relative;
height: 100%;
z-index: 999;
opacity: 1;
visibility: visible;
}
/*progress header*/
#progress_header {
overflow: hidden;
margin: 0 auto 30px;
padding: 0;
}
#progress_header li {
list-style-type: none;
width: 33.33%;
float: left;
position: relative;
font-size: 16px;
font-weight: bold;
font-family: monospace;
color: #fff;
text-transform: uppercase;
}
#progress_header li:after {
width: 35px;
line-height: 35px;
display: block;
font-size: 22px;
color: #888;
font-family: monospace;
background-color: #fff;
border-radius: 100px;
margin: 0 auto;
background-repeat: no-repeat;
font-family: 'Roboto', sans-serif;
}
#progress_header li:nth-child(1):after {
content: "1";
}
#progress_header li:nth-child(2):after {
content: "2";
}
#progress_header li:nth-child(3):after {
content: "3";
}
#progress_header li:before {
content: '';
width: 100%;
height: 5px;
background: #fff;
position: absolute;
left: -50%;
top: 50%;
z-index: -1;
}
#progress_header li:first-child:before {
content: none;
}
#progress_header li.active:before,
#progress_header li.active:after {
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
color: #fff !important;
transition: all 0.5s;
}
/*title*/
.title-box {
width: 100%;
margin: 0 0 30px 0;
}
.title-box h2 {
font-size: 22px;
text-transform: uppercase;
color: #2C3E50;
margin: 0;
font-family: cursive;
display: inline-block;
position: relative;
padding: 0 0 10px 0;
font-family: 'Roboto', sans-serif;
}
.title-box h2:before {
content: "";
background: #6ddc8b;
width: 70px;
height: 2px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin: 0 auto;
display: block;
}
.title-box h2:after {
content: "";
background: #6ddc8b;
width: 50px;
height: 2px;
position: absolute;
bottom: -5px;
left: 0;
right: 0;
margin: 0 auto;
display: block;
}
/*Input and Button*/
.multistep-box {
background: white;
border: 0 none;
border-radius: 3px;
box-shadow: 1px 1px 55px 3px rgba(255, 255, 255, 0.4);
padding: 30px 30px;
box-sizing: border-box;
width: 80%;
margin: 0 10%;
position: absolute;
}
.multistep-box:not(:first-of-type) {
display: none;
}
.multistep-box p {
margin: 0 0 12px 0;
text-align: left;
}
.multistep-box span {
font-size: 12px;
color: #FF0000;
}
input, textarea {
padding: 15px;
border: 1px solid #ccc;
border-radius: 3px;
margin: 0;
width: 100%;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
color: #2C3E50;
font-size: 13px;
transition: all 0.5s;
outline: none;
}
input:focus, textarea:focus {
box-shadow: inset 0px 0px 50px 2px rgb(0,0,0,0.1);
}
input.box_error, textarea.box_error {
border-color: #FF0000;
box-shadow: inset 0px 0px 50px 2px rgb(255,0,0,0.1);
}
input.box_error:focus, textarea.box_error:focus {
box-shadow: inset 0px 0px 50px 2px rgb(255,0,0,0.1);
}
p.nxt-prev-button {
margin: 25px 0 0 0;
text-align: center;
}
.action-button {
width: 100px;
font-weight: bold;
color: white;
border: 0 none;
border-radius: 1px;
cursor: pointer;
padding: 10px 5px;
margin: 0 5px;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b);
transition: all 0.5s;
}
.action-button:hover,
.action-button:focus {
box-shadow: 0 0 0 2px white, 0 0 0 3px #6ce199;
}
.form_submited #multistep_form {
opacity: 0;
visibility: hidden;
}
.form_submited h1 {
-webkit-background-clip: text;
transform: translate(0%, 0%);
-webkit-transform: translate(0%, 0%);
transition: all 0.3s ease;
opacity: 1;
visibility: visible;
}
h1 {
margin: 0;
text-align: center;
font-size: 90px;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
background-image: linear-gradient(to right top, #35e8c3, #36edbb, #3df2b2, #4af7a7, #59fb9b) !important;
color: transparent;
-webkit-background-clip: text;
-webkit-background-clip: text;
transform: translate(0%, -80%);
-webkit-transform: translate(0%, -80%);
transition: all 0.3s ease;
opacity: 0;
visibility: hidden;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
text-align: center;
top: 50%;
}
h3{
color:#fff;
text-align:center;
margin-bottom:20px;
}
Add jQuery:
var current_slide, next_slide, previous_slide;
var left, opacity, scale;
var animation;
var error = false;
// email validation
$("#email").keyup(function() {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($("#email").val())) {
$("#error-email").text('Please enter an Email addres.');
$("#email").addClass("box_error");
error = true;
} else {
$("#error-email").text('');
error = false;
$("#email").removeClass("box_error");
}
});
// password validation
$("#pass").keyup(function() {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != '') {
$("#error-pass").text('');
error = false;
$("#pass").removeClass("box_error");
}
if (pass != cpass && cpass != '') {
$("#error-cpass").text('Password and Confirm Password is not matched.');
error = true;
} else {
$("#error-cpass").text('');
error = false;
}
});
// confirm password validation
$("#cpass").keyup(function() {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != cpass) {
$("#error-cpass").text('Please enter the same Password as above.');
$("#cpass").addClass("box_error");
error = true;
} else {
$("#error-cpass").text('');
error = false;
$("#cpass").removeClass("box_error");
}
});
// twitter
$("#twitter").keyup(function() {
var twitterReg = /https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/;
if (!twitterReg.test($("#twitter").val())) {
$("#error-twitter").text('Twitter link is not valid.');
$("#twitter").addClass("box_error");
error = true;
} else {
$("#error-twitter").text('');
error = false;
$("#twitter").removeClass("box_error");
}
});
// facebook
$("#facebook").keyup(function() {
var facebookReg = /^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/;
if (!facebookReg.test($("#facebook").val())) {
$("#error-facebook").text('Facebook link is not valid.');
$("#facebook").addClass("box_error");
error = true;
} else {
$("#error-facebook").text('');
error = false;
$("#facebook").removeClass("box_error");
}
});
// linkedin
$("#linkedin").keyup(function() {
var linkedinReg = /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (!linkedinReg.test($("#linkedin").val())) {
$("#error-linkedin").text('Linkedin link is not valid.');
$("#linkedin").addClass("box_error");
error = true;
} else {
$("#error-linkedin").text('');
error = false;
$("#linkedin").removeClass("box_error");
}
});
// first name
$("#fname").keyup(function() {
var fname = $("#fname").val();
if (fname == '') {
$("#error-fname").text('Enter your First name.');
$("#fname").addClass("box_error");
error = true;
} else {
$("#error-fname").text('');
error = false;
}
if ((fname.length <= 2) || (fname.length > 20)) {
$("#error-fname").text("User length must be between 2 and 20 Characters.");
$("#fname").addClass("box_error");
error = true;
}
if (!isNaN(fname)) {
$("#error-fname").text("Only Characters are allowed.");
$("#fname").addClass("box_error");
error = true;
} else {
$("#fname").removeClass("box_error");
}
});
// last name
$("#lname").keyup(function() {
var lname = $("#lname").val();
if (lname != lname) {
$("#error-lname").text('Enter your Last name.');
$("#lname").addClass("box_error");
error = true;
} else {
$("#error-lname").text('');
error = false;
}
if ((lname.length <= 2) || (lname.length > 20)) {
$("#error-lname").text("User length must be between 2 and 20 Characters.");
$("#lname").addClass("box_error");
error = true;
}
if (!isNaN(lname)) {
$("#error-lname").text("Only Characters are allowed.");
$("#lname").addClass("box_error");
error = true;
} else {
$("#lname").removeClass("box_error");
}
});
// phone
$("#phone").keyup(function() {
var phone = $("#phone").val();
if (phone != phone) {
$("#error-phone").text('Enter your Phone number.');
$("#phone").addClass("box_error");
error = true;
} else {
$("#error-phone").text('');
error = false;
}
if (phone.length != 10) {
$("#error-phone").text("Mobile number must be of 10 Digits only.");
$("#phone").addClass("box_error");
error = true;
} else {
$("#phone").removeClass("box_error");
}
});
// address
$("#address").keyup(function() {
var address = $("#address").val();
if (address != address) {
$("#error-address").text('Enter your Address.');
$("#address").addClass("box_error");
error = true;
} else {
$("#error-address").text('');
error = false;
$("#address").removeClass("box_error");
}
});
// first step validation
$(".fs_next_btn").click(function() {
// email
if ($("#email").val() == '') {
$("#error-email").text('Please enter an email address.');
$("#email").addClass("box_error");
error = true;
} else {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($("#email").val())) {
$("#error-email").text('Please insert a valid email address.');
error = true;
} else {
$("#error-email").text('');
$("#email").removeClass("box_error");
}
}
// password
if ($("#pass").val() == '') {
$("#error-pass").text('Please enter a password.');
$("#pass").addClass("box_error");
error = true;
}
if ($("#cpass").val() == '') {
$("#error-cpass").text('Please enter a Confirm password.');
$("#cpass").addClass("box_error");
error = true;
} else {
var pass = $("#pass").val();
var cpass = $("#cpass").val();
if (pass != cpass) {
$("#error-cpass").text('Please enter the same password as above.');
error = true;
} else {
$("#error-cpass").text('');
$("#pass").removeClass("box_error");
$("#cpass").removeClass("box_error");
}
}
// animation
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// second step validation
$(".ss_next_btn").click(function() {
// twitter
if ($("#twitter").val() == '') {
$("#error-twitter").text('twitter link is required.');
$("#twitter").addClass("box_error");
error = true;
} else {
var twitterReg = /https?:\/\/twitter\.com\/(#!\/)?[a-z0-9_]+$/;
if (!twitterReg.test($("#twitter").val())) {
$("#error-twitter").text('Twitter link is not valid.');
error = true;
} else {
$("#error-twitter").text('');
$("#twitter").removeClass("box_error");
}
}
// facebook
if ($("#facebook").val() == '') {
$("#error-facebook").text('Facebook link is required.');
$("#facebook").addClass("box_error");
error = true;
} else {
var facebookReg = /^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/;
if (!facebookReg.test($("#facebook").val())) {
$("#error-facebook").text('Facebook link is not valid.');
error = true;
$("#facebook").addClass("box_error");
} else {
$("#error-facebook").text('');
}
}
// linkedin
if ($("#linkedin").val() == '') {
$("#error-linkedin").text('Linkedin link is required.');
$("#linkedin").addClass("box_error");
error = true;
} else {
var linkedinReg = /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (!linkedinReg.test($("#linkedin").val())) {
$("#error-linkedin").text('Linkedin link is not valid.');
error = true;
} else {
$("#error-linkedin").text('');
$("#linkedin").removeClass("box_error");
}
}
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// third step validation
$(".ts_next_btn").click(function() {
// first name
if ($("#fname").val() == '') {
$("#error-fname").text('Enter your First name.');
$("#fname").addClass("box_error");
error = true;
} else {
var fname = $("#fname").val();
if (fname != fname) {
$("#error-fname").text('First name is required.');
error = true;
} else {
$("#error-fname").text('');
error = false;
$("#fname").removeClass("box_error");
}
if ((fname.length <= 2) || (fname.length > 20)) {
$("#error-fname").text("User length must be between 2 and 20 Characters.");
error = true;
}
if (!isNaN(fname)) {
$("#error-fname").text("Only Characters are allowed.");
error = true;
} else {
$("#fname").removeClass("box_error");
}
}
// last name
if ($("#lname").val() == '') {
$("#error-lname").text('Enter your Last name.');
$("#lname").addClass("box_error");
error = true;
} else {
var lname = $("#lname").val();
if (lname != lname) {
$("#error-lname").text('Last name is required.');
error = true;
} else {
$("#error-lname").text('');
error = false;
}
if ((lname.length <= 2) || (lname.length > 20)) {
$("#error-lname").text("User length must be between 2 and 20 Characters.");
error = true;
}
if (!isNaN(lname)) {
$("#error-lname").text("Only Characters are allowed.");
error = true;
} else {
$("#lname").removeClass("box_error");
}
}
// phone
if ($("#phone").val() == '') {
$("#error-phone").text('Enter your Phone number.');
$("#phone").addClass("box_error");
error = true;
} else {
var phone = $("#phone").val();
if (phone != phone) {
$("#error-phone").text('Phone number is required.');
error = true;
} else {
$("#error-phone").text('');
error = false;
}
if (phone.length != 10) {
$("#error-phone").text("Mobile number must be of 10 Digits only.");
error = true;
} else {
$("#phone").removeClass("box_error");
}
}
// address
if ($("#address").val() == '') {
$("#error-address").text('Enter your Address.');
$("#address").addClass("box_error");
error = true;
} else {
var address = $("#address").val();
if (address != address) {
$("#error-address").text('Address is required.');
error = true;
} else {
$("#error-address").text('');
$("#address").removeClass("box_error");
error = false;
}
}
if (!error) {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
next_slide = $(this).parent().parent().next();
$("#progress_header li").eq($(".multistep-box").index(next_slide)).addClass("active");
next_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 1 - (1 - now) * 0.2;
left = (now * 50) + "%";
opacity = 1 - now;
current_slide.css({
'transform': 'scale(' + scale + ')'
});
next_slide.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
}
});
// previous
$(".previous").click(function() {
if (animation) return false;
animation = true;
current_slide = $(this).parent().parent();
previous_slide = $(this).parent().parent().prev();
$("#progress_header li").eq($(".multistep-box").index(current_slide)).removeClass("active");
previous_slide.show();
current_slide.animate({
opacity: 0
}, {
step: function(now, mx) {
scale = 0.8 + (1 - now) * 0.2;
left = ((1 - now) * 50) + "%";
opacity = 1 - now;
current_slide.css({
'left': left
});
previous_slide.css({
'transform': 'scale(' + scale + ')',
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_slide.hide();
animation = false;
},
easing: 'easeInOutBack'
});
});
$(".submit_btn").click(function() {
if (!error){
$(".main").addClass("form_submited");
}
return false;
})
Output:
Original article source at: https://websolutionstuff.com/
1673588880
A Swift Package to easily validate your properties using Property Wrappers 👮
import SwiftUI
import ValidatedPropertyKit
struct LoginView: View {
@Validated(!.isEmpty && .isEmail)
var mailAddress = String()
@Validated(.range(8...))
var password = String()
var body: some View {
List {
TextField(
"E-Mail",
text: self.$mailAddress
)
if self._mailAddress.isInvalidAfterChanges {
Text(verbatim: "Please enter a valid E-Mail address.")
}
TextField(
"Password",
text: self.$password
)
if self._password.isInvalidAfterChanges {
Text(verbatim: "Please enter a valid password.")
}
Button {
print("Login", self.mailAddress, self.password)
} label: {
Text(verbatim: "Submit")
}
.validated(
self._mailAddress,
self._password
)
}
}
}
To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift
:
dependencies: [
.package(url: "https://github.com/SvenTiigi/ValidatedPropertyKit.git", from: "0.0.6")
]
Or navigate to your Xcode project then select Swift Packages
, click the “+” icon and search for ValidatedPropertyKit
.
If you prefer not to use any of the aforementioned dependency managers, you can integrate ValidatedPropertyKit into your project manually. Simply drag the Sources
Folder into your Xcode project.
The @Validated
attribute allows you to specify a validation alongside to the declaration of your property.
Note: @Validated supports SwiftUI View updates and will basically work the same way as @State does.
@Validated(!.isEmpty)
var username = String()
@Validated(.hasPrefix("https"))
var avatarURL: String?
If @Validated
is applied on an optional type e.g. String?
you can specify whether the validation should fail or succeed when the value is nil
.
@Validated(
.isURL && .hasPrefix("https"),
isNilValid: true
)
var avatarURL: String?
By default the argument
nilValidation
is set to.constant(false)
In addition the SwiftUI.View
extension validated()
allows you to disable or enable a certain SwiftUI.View
based on your @Validated
properties. The validated()
function will disable the SwiftUI.View
if at least one of the passed in @Validated
properties evaluates to false
.
@Validated(!.isEmpty && .contains("@"))
var mailAddress = String()
@Validated(.range(8...))
var password = String()
Button(
action: {},
label: { Text("Submit") }
)
.validated(self._mailAddress && self._password)
By using the underscore notation you are passing the
@Validated
property wrapper to thevalidated()
function
Each @Validated
attribute will be initialized with a Validation
which can be initialized with a simple closure that must return a Bool
value.
@Validated(.init { value in
value.isEmpty
})
var username = String()
Therefore, ValidatedPropertyKit comes along with many built-in convenience functions for various types and protocols.
@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem = String()
@Validated(.equals(42))
var magicNumber = Int()
@Validated(.keyPath(\.isEnabled, .equals(true)))
var object = MyCustomObject()
Head over the Predefined Validations section to learn more
Additionally, you can extend the Validation
via conditional conformance to easily declare your own Validations.
extension Validation where Value == Int {
/// Will validate if the Integer is the meaning of life
static var isMeaningOfLife: Self {
.init { value in
value == 42
}
}
}
And apply them to your validated property.
@Validated(.isMeaningOfLife)
var number = Int()
You can access the isValid
state at anytime by using the underscore notation to directly access the @Validated
property wrapper.
@Validated(!.isEmpty)
var username = String()
username = "Mr.Robot"
print(_username.isValid) // true
username = ""
print(_username.isValid) // false
Validation Operators allowing you to combine multiple Validations like you would do with Bool values.
// Logical AND
@Validated(.hasPrefix("https") && .hasSuffix("png"))
var avatarURL = String()
// Logical OR
@Validated(.hasPrefix("Mr.") || .hasPrefix("Mrs."))
var name = String()
// Logical NOT
@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem = String()
The ValidatedPropertyKit
comes with many predefined common validations which you can make use of in order to specify a Validation
for your validated property.
KeyPath
The keyPath
validation will allow you to specify a validation for a given KeyPath
of the attributed property.
@Validated(.keyPath(\.isEnabled, .equals(true)))
var object = MyCustomObject()
Strings
A String property can be validated in many ways like contains
, hasPrefix
and even RegularExpressions
.
@Validated(.isEmail)
var string = String()
@Validated(.contains("Mr.Robot"))
var string = String()
@Validated(.hasPrefix("Mr."))
var string = String()
@Validated(.hasSuffix("OS"))
var string = String()
@Validated(.regularExpression("[0-9]+$"))
var string = String()
Equatable
A Equatable
type can be validated against a specified value.
@Validated(.equals(42))
var number = Int()
Sequence
A property of type Sequence
can be validated via the contains
or startsWith
validation.
@Validated(.contains("Mr.Robot", "Elliot"))
var sequence = [String]()
@Validated(.startsWith("First Entry"))
var sequence = [String]()
Collection
Every Collection
type offers the isEmpty
validation and the range
validation where you can easily declare the valid capacity.
@Validated(!.isEmpty)
var collection = [String]()
@Validated(.range(1...10))
var collection = [String]()
Comparable
A Comparable
type can be validated with all common comparable operators.
@Validated(.less(50))
var comparable = Int()
@Validated(.lessOrEqual(50))
var comparable = Int()
@Validated(.greater(50))
var comparable = Int()
@Validated(.greaterOrEqual(50))
var comparable = Int()
Author: SvenTiigi
Source Code: https://github.com/SvenTiigi/ValidatedPropertyKit
License: MIT license
1666156140
Swift 5.3 framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Features | |
---|---|
☎️ | Validate, normalize and extract the elements of any phone number string. |
💯 | Simple Swift syntax and a lightweight readable codebase. |
🏁 | Fast. 1000 parses -> ~0.4 seconds. |
📚 | Best-in-class metadata from Google's libPhoneNumber project. |
🏆 | Fully tested to match the accuracy of Google's JavaScript implementation of libPhoneNumber. |
📱 | Built for iOS. Automatically grabs the default region code from the phone. |
📝 | Editable (!) AsYouType formatter for UITextField. |
🇺🇸 | Convert country codes to country names and vice versa |
Import PhoneNumberKit at the top of the Swift file that will interact with a phone number.
import PhoneNumberKit
All of your interactions with PhoneNumberKit happen through a PhoneNumberKit object. The first step you should take is to allocate one.
A PhoneNumberKit instance is relatively expensive to allocate (it parses the metadata and keeps it in memory for the object's lifecycle), you should try and make sure PhoneNumberKit is allocated once and deallocated when no longer needed.
let phoneNumberKit = PhoneNumberKit()
To parse a string, use the parse function. The region code is automatically computed but can be overridden if needed. PhoneNumberKit automatically does a hard type validation to ensure that the object created is valid, this can be quite costly performance-wise and can be turned off if needed.
do {
let phoneNumber = try phoneNumberKit.parse("+33 6 89 017383")
let phoneNumberCustomDefaultRegion = try phoneNumberKit.parse("+44 20 7031 3000", withRegion: "GB", ignoreType: true)
}
catch {
print("Generic parser error")
}
If you need to parse and validate a large amount of numbers at once, PhoneNumberKit has a special, lightning fast array parsing function. The default region code is automatically computed but can be overridden if needed. Here you can also ignore hard type validation if it is not necessary. Invalid numbers are ignored in the resulting array.
let rawNumberArray = ["0291 12345678", "+49 291 12345678", "04134 1234", "09123 12345"]
let phoneNumbers = phoneNumberKit.parse(rawNumberArray)
let phoneNumbersCustomDefaultRegion = phoneNumberKit.parse(rawNumberArray, withRegion: "DE", ignoreType: true)
PhoneNumber objects are immutable Swift structs with the following properties:
phoneNumber.numberString
phoneNumber.countryCode
phoneNumber.nationalNumber
phoneNumber.numberExtension
phoneNumber.type // e.g Mobile or Fixed
Formatting a PhoneNumber object into a string is also very easy
phoneNumberKit.format(phoneNumber, toType: .e164) // +61236618300
phoneNumberKit.format(phoneNumber, toType: .international) // +61 2 3661 8300
phoneNumberKit.format(phoneNumber, toType: .national) // (02) 3661 8300
To use the AsYouTypeFormatter, just replace your UITextField with a PhoneNumberTextField (if you are using Interface Builder make sure the module field is set to PhoneNumberKit).
You can customize your TextField UI in the following ways
withFlag
will display the country code for the currentRegion
. The flagButton
is displayed in the leftView
of the text field with it's size set based off your text size.withExamplePlaceholder
uses attributedPlaceholder
to show an example number for the currentRegion
. In addition when withPrefix
is set, the country code's prefix will automatically be inserted and removed when editing changes.PhoneNumberTextField automatically formats phone numbers and gives the user full editing capabilities. If you want to customize you can use the PartialFormatter directly. The default region code is automatically computed but can be overridden if needed (see the example given below).
class MyGBTextField: PhoneNumberTextField {
override var defaultRegion: String {
get {
return "GB"
}
set {} // exists for backward compatibility
}
}
let textField = PhoneNumberTextField()
PartialFormatter().formatPartial("+336895555") // +33 6 89 55 55
You can also query countries for a dialing code or the dialing code for a given country
phoneNumberKit.countries(withCode: 33)
phoneNumberKit.countryCode(for: "FR")
You can access the metadata powering PhoneNumberKit yourself, this enables you to program any behaviours as they may be implemented in PhoneNumberKit itself. It does mean you are exposed to the less polished interface of the underlying file format. If you program something you find useful please push it upstream!
phoneNumberKit.metadata(for: "AU")?.mobile?.exampleNumber // 412345678
The Swift Package Manager is now the preferred tool for distributing PhoneNumberKit.
From Xcode 11+ :
https://github.com/marmelroy/PhoneNumberKit.git
in the "Choose Package Repository" dialog.For more info, read Adding Package Dependencies to Your App from Apple.
Alternatively, you can also add PhoneNumberKit to your Package.swift
file:
dependencies: [
.package(url: "https://github.com/marmelroy/PhoneNumberKit", from: "3.4.0")
]
Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthage
To integrate PhoneNumberKit into your Xcode project using Carthage, specify it in your Cartfile
:
github "marmelroy/PhoneNumberKit"
pod 'PhoneNumberKit', :git => 'https://github.com/marmelroy/PhoneNumberKit'
Author: Marmelroy
Source Code: https://github.com/marmelroy/PhoneNumberKit
License: MIT license
1662542961
In today's post we will learn about 7 Best React Validated/Masked Input Libraries.
Vanilla javascript input mask
npm install react-imask
import { useRef } from 'react';
import { IMaskInput } from 'react-imask';
// use ref to get access to internal "masked = ref.current.maskRef"
const ref = useRef(null);
<IMaskInput
mask={Number}
radix="."
value="123"
unmask={true} // true|false|'typed'
ref={ref}
inputRef={el => this.input = el} // access to nested input
// DO NOT USE onChange TO HANDLE CHANGES!
// USE onAccept INSTEAD
onAccept={
// depending on prop above first argument is
// `value` if `unmask=false`,
// `unmaskedValue` if `unmask=true`,
// `typedValue` if `unmask='typed'`
(value, mask) => console.log(value)
}
// ...and more mask props in a guide
// input props also available
placeholder='Enter number here'
/>
React Number format is a input formatter library with a sohpisticated and light weight caret engine.
Using npm
npm install react-number-format
Using yarn
yarn add react-number-format
Numeric Format
import { NumericFormat } from 'react-number-format';
Pattern Format
import { PatternFormat } from 'react-number-format';
Cleave.js has a simple purpose: to help you format input text content automatically.
npm install --save cleave.js
cleave.js is available on jsDelivr and on cdnjs.com
Grab file from dist directory
Simply include
<script src="cleave.min.js"></script>
<script src="cleave-phone.{country}.js"></script>
cleave-phone.{country}.js
addon is only required when phone shortcut mode is enabled. See more in documentation: phone lib addon section
Then have a text field
<input class="input-phone" type="text"/>
Now in your JavaScript
var cleave = new Cleave('.input-phone', {
phone: true,
phoneRegionCode: '{country}'
});
React component for entering and validating PIN code.
npm i --save react-code-input
...
<ReactCodeInput type='number' fields={6} />
...
...
<ReactCodeInput type='text' fields={6} />
...
...
<ReactCodeInput type='password' fields={6} />
...
import { reactCodeInput } from 'CodeInputField.scss'
...
const props = {
className: reactCodeInput,
inputStyle: {
fontFamily: 'monospace',
margin: '4px',
MozAppearance: 'textfield',
width: '15px',
borderRadius: '3px',
fontSize: '14px',
height: '26px',
paddingLeft: '7px',
backgroundColor: 'black',
color: 'lightskyblue',
border: '1px solid lightskyblue'
},
inputStyleInvalid: {
fontFamily: 'monospace',
margin: '4px',
MozAppearance: 'textfield',
width: '15px',
borderRadius: '3px',
fontSize: '14px',
height: '26px',
paddingLeft: '7px',
backgroundColor: 'black',
color: 'red',
border: '1px solid red'
}
}
...
<ReactCodeInput type='number' fields={6} {...props}/>
...
A React component for <input>
masking, built on top of inputmask-core.
npm install react-maskedinput --save
Give MaskedInput
a mask
and an onChange
callback:
import React from 'react'
import MaskedInput from 'react-maskedinput'
class CreditCardDetails extends React.Component {
state = {
card: '',
expiry: '',
ccv: ''
}
_onChange = (e) => {
this.setState({[e.target.name]: e.target.value})
}
render() {
return <div className="CreditCardDetails">
<label>
Card Number:{' '}
<MaskedInput mask="1111 1111 1111 1111" name="card" size="20" onChange={this._onChange}/>
</label>
<label>
Expiry Date:{' '}
<MaskedInput mask="11/1111" name="expiry" placeholder="mm/yyyy" onChange={this._onChange}/>
</label>
<label>
CCV:{' '}
<MaskedInput mask="111" name="ccv" onChange={this._onChange}/>
</label>
</div>
}
}
Create some wrapper components if you have a masking configuration which will be reused:
function CustomInput(props) {
return <MaskedInput
mask="1111-WW-11"
placeholder="1234-WW-12"
size="11"
{...props}
formatCharacters={{
'W': {
validate(char) { return /\w/.test(char ) },
transform(char) { return char.toUpperCase() }
}
}}
/>
}
Input masking component for React. Made with attention to UX
Installation
npm install react-input-mask@next --save
react-input-mask requires React 16.8.0 or later. If you need support for older versions, use version 2.
Usage
import React from "react"
import InputMask from "react-input-mask";
function DateInput(props) {
return <InputMask mask="99/99/9999" onChange={props.onChange} value={props.value} />;
}
React component for an input field
npm install react-currency-input-field
or
yarn add react-currency-input-field
import CurrencyInput from 'react-currency-input-field';
<CurrencyInput
id="input-example"
name="input-name"
placeholder="Please enter a number"
defaultValue={1000}
decimalsLimit={2}
onValueChange={(value, name) => console.log(value, name)}
/>;
Thank you for following this article.
BEST Ways to Handle and Validate React Forms without a Library
1662104640
A ValueNotifier
that validates a value against a collection of customizable rules.
You can create your own set of rules by inheriting ValidationRule<T>
Let's say we create a rule that validates inputs that are required callled RequiredRule
import 'package:validation_notifier/validation_notifier.dart';
class RequiredStringRule extends ValidationRule<String> {
const RequiredStringRule();
@override
String get errorMessage => 'This field is required';
@override
bool checkIsValid(String? value) {
return value?.isNotEmpty ?? false;
}
}
Another rule that validates string inputs requiring them to have a email format called EmailFormatRule
import 'package:validation_notifier/validation_notifier.dart';
class EmailFormatRule extends ValidationRule<String> {
static final emailRegex = RegExp(
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');
const EmailFormatRule();
@override
String get errorMessage => 'Invalid email format';
@override
bool checkIsValid(String? value) {
if (value == null) {
return false;
} else {
return RegularExpressions.emailRegex.hasMatch(value);
}
}
}
You can add your previously created rules to a ValidationNotifier<T>
final email = ValidationNotifier<String>(rules: const [
RequiredRule(),
EmailFormatRule(),
]);
Use email
in a ValueListenableBuilder
ValueListenableBuilder<ValidationResult<String>>(
valueListenable: email,
builder: (context, value, child) {
return TextFormField(
onChanged: email.update,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: InputDecoration(
labelText: 'Email',
errorText: value.errorMessage,
),
);
},
)
Call ValidationNotifier<T>.validate()
to validate valueToValidate
using the rules you defined.
// A callback of a button for logging-in
void onLogin() {
final validationResult = email.validate();
if (evalidationResult.isValid) {
// Valid
} else {
// Invalid
}
}
ValidationNotifier<T>.value
will be set and other calls to remaining rules will be canceled.ValidationNotifier<T>
constructor.Run this command:
With Flutter:
$ flutter pub add validation_notifier
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
validation_notifier: ^1.4.6
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:validation_notifier/validation_notifier.dart';
example/lib/main.dart
import 'package:example/validation_rules.dart';
import 'package:flutter/material.dart';
import 'package:validation_notifier/validation_notifier.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: LayoutBuilder(
builder: (context, constraints) {
return Center(
child: Container(
padding: const EdgeInsets.all(24),
constraints: BoxConstraints(
maxWidth: 512,
maxHeight: constraints.maxHeight,
),
child: const _LoginForm(),
),
);
},
),
);
}
}
class _LoginForm extends StatefulWidget {
const _LoginForm({Key? key}) : super(key: key);
@override
_LoginFormState createState() => _LoginFormState();
}
class _LoginFormState extends State<_LoginForm> {
final email = ValidationNotifier<String>(
rules: const [
RequiredStringRule(),
EmailFormatRule(),
],
);
final password = ValidationNotifier<String>(
rules: const [
RequiredStringRule(),
StringLengthRule(8),
],
);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<ValidationResult<String>>(
valueListenable: email,
builder: (context, value, child) {
return TextFormField(
onChanged: email.update,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
decoration: InputDecoration(
labelText: 'Email',
errorText: value.errorMessage,
),
);
},
),
const SizedBox(height: 24),
ValueListenableBuilder<ValidationResult<String>>(
valueListenable: password,
builder: (context, value, child) {
return TextFormField(
onChanged: password.update,
decoration: InputDecoration(
labelText: 'Password',
errorText: value.errorMessage,
),
obscureText: true,
);
},
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _onLogin,
child: const Text('LOGIN'),
)
],
);
}
void _onLogin() {
final emailResult = email.validate();
final passwordResult = password.validate();
if (emailResult.isValid && passwordResult.isValid) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('All fields are valid')));
} else {
print('Email error: ${emailResult.errorMessage}');
print('Password error: ${passwordResult.errorMessage}');
}
}
}
Author: Cross-solutions
Source Code: https://github.com/cross-solutions/flutter-validation-notifier
License:
1661618074
credit_card_validator | Credit Card Validator
A Dart package that validates credit card numbers, expiration dates, and security codes (CVV/CVC) of a credit card. It also determines the type of credit card as part of the validation process.
This package should be used to quickly validate credit card data inputs and provide feedback to the user in your application's UI. It includes support for "potentially valid" inputs so that you can appropriately display the results to the user as they type.
Important: This package does not verify the information with the user's bank or credit company. Please use a payment processing service like Stripe or Braintree for true verification and validation of the user's payment info.
Installing
Add dependency to pubspec.yaml
Get the current version in the 'Installing' tab on pub.dartlang.org
dependencies:
credit_card_validator: *current-version*
import 'package:credit_card_validator/credit_card_validator.dart';
Usage
A basic example
import 'package:credit_card_validator/credit_card_validator.dart';
class CreditCardValidationBloc {
CreditCardValidator _ccValidator = CreditCardValidator()
bool validateCreditCardInfo(string ccNum, string expDate, string cvv, ...) {
var ccNumResults = _ccValidator.validateCCNum(ccNum);
var expDateResults = _ccValidator.validateExpDate(expDate);
var cvvResults = _ccValidator.validateCVV(cvv, ccNumResults.ccType);
...
if(ccNumResults.isPotentiallyValid) {
# Call UI code that shows to the user their credit card number is invalid
displayInvalidCardNumber();
}
}
}
Features
Original Repo
This package is based off of Braintree's Credit Card Validator JS package
Related Repos
Author
Cholojuanito (Tanner Davis) - Creator and repo owner - Github Profile
Support
If you think this package is helpful, tell your friends, give it a star on GitHub, and a like on pub.dev
License
This project is licensed under the MIT License - see the LICENSE file for more details
Run this command:
With Dart:
$ dart pub add credit_card_validator
With Flutter:
$ flutter pub add credit_card_validator
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
credit_card_validator: ^2.0.1
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:credit_card_validator/credit_card_validator.dart';
Example usage
Download Details:
Author: cholojuanito
Source Code: https://github.com/cholojuanito/credit_card_validator
1660579102
Utility to check environment variables using JSON schema, Ajv, and dotenv.
npm i env-schema
const envSchema = require('env-schema')
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema: schema,
data: data, // optional, default: process.env
dotenv: true // load .env if it is there, default: false
// or you can pass DotenvConfigOptions
// dotenv: {
// path: '/custom/path/to/.env'
// }
})
console.log(config)
// output: { PORT: 3000 }
Optionally, the user can supply their own ajv instance:
const envSchema = require('env-schema')
const Ajv = require('ajv')
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: new Ajv({
allErrors: true,
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allowUnionTypes: true
})
})
console.log(config)
// output: { PORT: 3000 }
It is possible to enhance the default ajv instance providing the customOptions
function parameter. This example shows how to use the format
keyword in your schemas.
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: {
customOptions (ajvInstance) {
require('ajv-formats')(ajvInstance)
return ajvInstance
}
}
})
Note that it is mandatory returning the ajv instance.
It is also possible to use fluent-json-schema:
const envSchema = require('env-schema')
const S = require('fluent-json-schema')
const config = envSchema({
schema: S.object().prop('port', S.number().default(3000).required()),
data: data, // optional, default: process.env
dotenv: true, // load .env if it is there, default: false
expandEnv: true, // use dotenv-expand, default: false
})
console.log(config)
// output: { PORT: 3000 }
NB Support for additional properties in the schema is disabled for this plugin, with the additionalProperties
flag set to false
internally.
This library supports the following Ajv custom keywords:
separator
Type: string
Applies to type: string
When present, the provided schema value will be split on this value.
Example:
const envSchema = require('env-schema')
const schema = {
type: 'object',
required: [ 'ALLOWED_HOSTS' ],
properties: {
ALLOWED_HOSTS: {
type: 'string',
separator: ','
}
}
}
const data = {
ALLOWED_HOSTS: '127.0.0.1,0.0.0.0'
}
const config = envSchema({
schema: schema,
data: data, // optional, default: process.env
dotenv: true // load .env if it is there, default: false
})
// config.data => ['127.0.0.1', '0.0.0.0']
The ajv keyword definition objects can be accessed through the property keywords
on the envSchema
function:
const envSchema = require('env-schema')
const Ajv = require('ajv')
const schema = {
type: 'object',
properties: {
names: {
type: 'string',
separator: ','
}
}
}
const config = envSchema({
schema: schema,
data: data,
dotenv: true,
ajv: new Ajv({
allErrors: true,
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allowUnionTypes: true,
keywords: [envSchema.keywords.separator]
})
})
console.log(config)
// output: { names: ['foo', 'bar'] }
You can specify the type of your config
:
import envSchema from 'env-schema';
interface Env {
PORT: number;
}
const schema = {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'number',
default: 3000
}
}
}
const config = envSchema<Env>({
schema,
})
If no type is specified the config
will have the EnvSchemaData
type.
export type EnvSchemaData = {
[key: string]: unknown;
}
Kindly sponsored by Mia Platform and NearForm.
Author: Fastify
Source Code: https://github.com/fastify/env-schema
License: MIT license
1660570363
This package is a validation package which helps you to validate strings.If the string has correct format the validate method returns null and if string does not match to what you like validate method returns error message.
1-min length
2-max length
3-required (not empty)
4-is number
5-is alphabet
6-is email
7-contains a upperCase
8-contains a special characters
For using this package you just to need add it to your pubspec.yaml file.
strings_validator :last version
After that import it where ever you want to use it.
import 'package:strings_validator/validation/validation.dart';
And finally call validate method on each string you are trying to validate.This method has two param first one is what option you want and second one is a map of message which you want to will be overrode
1-max:3
2-min:2
3-required
4-number
5-alpha
6-email
7-upperCase
8-specialChar
String test = 'this is your string';
const String pattern = 'min:6|max:12|email|required';
Map<String,String> MyMessages= {
'max':'max length of your input should be 12 char',
'min':'min length of your input should be 6 char',
'email':'your input is not a email and its format is incorrect'
};
String? result= test.validate(pattern,messages:MyMessages);
print(result); //if string will be matched demonstrates null else demonstrates error message
You can contribute on github https://github.com/mjdarvishi
Run this command:
With Flutter:
$ flutter pub add strings_validator
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
strings_validator: ^0.1.4
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:strings_validator/validation/exceptions/exceptions.dart';
import 'package:strings_validator/validation/messages.dart';
import 'package:strings_validator/validation/validation.dart';
import 'package:strings_validator/validation/validation.dart';
void testMethod() {
// options are:
//max:3
//min:2
//required
//number
//alpha
//email
//upperCase
//specialChar
String test = 'this is your string';
const pattern = 'min:6|max:12|email|required';
Map<String,String> myMessages= {
'max':'max length of your input should be 12 char',
'min':'min length of your input should be 6 char',
'email':'your input is not a email and its format is incorrect'
};
var result= test.validate(pattern,messages:myMessages);
// ignore: avoid_print
print(result); //if string will be matched demonstrates null else demonstrates error message
}
Download Details:
Author: mjdarvishi
Source Code: https://github.com/mjdarvishi/flutter_string_validatore