PHPackages                             tweekersnut/forms-lib - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. tweekersnut/forms-lib

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

tweekersnut/forms-lib
=====================

A comprehensive PHP forms library for Laravel and Core PHP with Bootstrap/Tailwind support, AJAX handling, and validation

v1.0.0(7mo ago)07MITPHPPHP ^8.0

Since Oct 18Pushed 7mo agoCompare

[ Source](https://github.com/TaranpreetSinghRayat/Forms-Lib)[ Packagist](https://packagist.org/packages/tweekersnut/forms-lib)[ RSS](/packages/tweekersnut-forms-lib/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

Forms Library - PHP
===================

[](#forms-library---php)

A comprehensive, flexible PHP forms library for Laravel and Core PHP with Bootstrap/Tailwind CSS support, AJAX handling, dynamic validation, and CSRF token protection.

Features
--------

[](#features)

- ✨ **Multiple Field Types** - Text, Email, Password, Textarea, Select, Checkbox, Radio, File, Hidden, and more
- 🎨 **CSS Framework Support** - Bootstrap 5 and Tailwind CSS with easy theme switching
- ✅ **Built-in Validation** - Email, URL, phone, date, numeric, and custom validators
- 🔄 **AJAX Support** - Complete AJAX form handling with real-time validation
- 🛡️ **CSRF Protection** - Built-in CSRF token generation and verification
- 🚀 **Laravel Integration** - Service provider, facades, and helper functions
- 📦 **Core PHP Compatible** - Works standalone without any framework
- 🎯 **Customizable** - Custom attributes, classes, IDs, and validation rules
- 📱 **Responsive** - Mobile-friendly form rendering
- 🏷️ **Shortcode System** - Create reusable forms for forums, CMS, and content platforms with callbacks

Installation
------------

[](#installation)

```
composer require tweekersnut/forms-lib
```

### Laravel Setup

[](#laravel-setup)

Add to your `config/app.php` providers:

```
'providers' => [
    // ...
    Tweekersnut\FormsLib\Laravel\FormsLibServiceProvider::class,
],

'aliases' => [
    // ...
    'Forms' => Tweekersnut\FormsLib\Laravel\Facades\FormsFacade::class,
]
```

Publish configuration:

```
php artisan vendor:publish --tag=forms-lib-config
```

Quick Start
-----------

[](#quick-start)

### Core PHP

[](#core-php)

```
use Tweekersnut\FormsLib\Core\FormBuilder;
use Tweekersnut\FormsLib\Fields\TextField;
use Tweekersnut\FormsLib\Fields\EmailField;
use Tweekersnut\FormsLib\Fields\SubmitField;

$form = new FormBuilder('contact_form', 'bootstrap');
$form->method('POST')->action('/submit');

$form->field(
    (new TextField('name'))
        ->label('Name')
        ->required()
        ->rule('min:2')
);

$form->field(
    (new EmailField('email'))
        ->label('Email')
        ->required()
);

$form->field(new SubmitField('submit', 'Send'));

echo $form->render();
```

### Laravel

[](#laravel)

```
use Tweekersnut\FormsLib\Laravel\Facades\FormsFacade as Forms;

$form = Forms::create('contact_form', 'bootstrap');
$form->method('POST')->action('/submit');

// Add fields...

echo $form->render();
```

Or use the helper:

```
$form = form('contact_form');
```

Field Types
-----------

[](#field-types)

- `TextField` - Text input with optional type (text, email, password, number, etc.)
- `EmailField` - Email input with validation
- `PasswordField` - Password input
- `NumberField` - Number input
- `PhoneField` - Phone number input
- `URLField` - URL input
- `DateField` - Date input
- `TimeField` - Time input
- `DateTimeField` - DateTime input
- `TextAreaField` - Textarea with configurable rows/cols
- `SelectField` - Dropdown select
- `CheckboxField` - Checkbox group
- `RadioField` - Radio button group
- `FileField` - File upload
- `HiddenField` - Hidden input
- `SubmitField` - Submit button
- `ResetField` - Reset button
- `ButtonField` - Generic button

Validation Rules
----------------

[](#validation-rules)

Built-in validators:

- `required` - Field is required
- `email` - Valid email format
- `numeric` - Numeric value
- `phone` - Valid phone number
- `url` - Valid URL
- `date` - Valid date
- `datetime` - Valid datetime
- `min:n` - Minimum length
- `max:n` - Maximum length
- `minvalue:n` - Minimum numeric value
- `maxvalue:n` - Maximum numeric value
- `match:value` - Match specific value

### Custom Validation

[](#custom-validation)

```
$validator = new Validator();
$validator->registerRule('custom_rule', function($value, $param, $field) {
    return strlen($value) > 5;
});
```

AJAX Handling
-------------

[](#ajax-handling)

### PHP Backend

[](#php-backend)

```
use Tweekersnut\FormsLib\AJAX\AjaxHandler;

if (AjaxHandler::isAjaxRequest()) {
    $handler = new AjaxHandler($form);

    if ($handler->validate()) {
        $handler->setSuccess(true)
            ->setMessage('Form submitted successfully')
            ->setData(['id' => 123]);
    }

    $handler->send();
}
```

### JavaScript Frontend

[](#javascript-frontend)

```

    const formHandler = new FormHandler('#myForm', {
        submitUrl: '/submit',
        onSuccess: function(response) {
            console.log('Success:', response);
        },
        onError: function(response) {
            console.log('Error:', response);
        }
    });

```

CSRF Token Protection
---------------------

[](#csrf-token-protection)

Protect your forms from Cross-Site Request Forgery attacks:

```
use Tweekersnut\FormsLib\Security\CsrfToken;

session_start();

// Initialize CSRF token
$csrf = new CsrfToken('_token');
$token = $csrf->getToken();

// Add token to form
$form->withCsrfToken($token);

// Verify token on submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$csrf->verifyRequest()) {
        die('Invalid CSRF token');
    }
    // Process form...
}
```

### CSRF Token Methods

[](#csrf-token-methods)

```
$csrf = new CsrfToken($tokenName);

$csrf->generate()           // Generate new token
$csrf->getToken()           // Get current token
$csrf->getTokenName()       // Get token field name
$csrf->verify($token)       // Verify specific token
$csrf->verifyRequest()      // Verify token from POST/GET
$csrf->regenerate()         // Regenerate token (after login)
$csrf->clear()              // Clear token
$csrf->setTokenLength($len) // Set token length
```

Themes
------

[](#themes)

### Bootstrap 5

[](#bootstrap-5)

```
$form = new FormBuilder('myform', 'bootstrap');
```

### Tailwind CSS

[](#tailwind-css)

```
$form = new FormBuilder('myform', 'tailwind');
```

Examples
--------

[](#examples)

See the `examples/` directory for complete working examples:

- `01-basic-form.php` - Basic form creation
- `02-form-with-validation.php` - Form validation
- `03-ajax-form.php` - AJAX form submission
- `04-csrf-token-form.php` - CSRF token protection

API Reference
-------------

[](#api-reference)

### FormBuilder

[](#formbuilder)

```
$form = new FormBuilder($name, $theme);

$form->method($method)           // Set HTTP method
$form->action($url)              // Set form action
$form->attributes($attrs)        // Add HTML attributes
$form->field($field)             // Add field
$form->values($data)             // Set field values
$form->errors($errors)           // Set validation errors
$form->validate($data)           // Validate data
$form->render()                  // Render complete form
$form->renderField($name)        // Render single field
$form->toArray()                 // Convert to array
$form->toJson()                  // Convert to JSON
```

### Field

[](#field)

```
$field->label($text)             // Set label
$field->value($value)            // Set value
$field->placeholder($text)       // Set placeholder
$field->help($text)              // Set help text
$field->required($bool)          // Mark as required
$field->rule($rule)              // Add validation rule
$field->rules($array)            // Add multiple rules
$field->attributes($attrs)       // Add HTML attributes
$field->addClass($class)         // Add CSS class
$field->id($id)                  // Set element ID
```

Shortcodes (Forums &amp; CMS)
-----------------------------

[](#shortcodes-forums--cms)

Create reusable forms that can be embedded in forum posts and CMS content using simple shortcode syntax:

```
use Tweekersnut\FormsLib\Shortcodes\FormShortcode;

// Create and configure form
$form = new FormBuilder('contact_form', 'bootstrap');
$form->field((new TextField('name'))->label('Name')->required());
$form->field((new EmailField('email'))->label('Email')->required());

// Create shortcode
$shortcode = new FormShortcode($form);

// Add success callback
$shortcode->onSuccess(function ($data, $shortcode) {
    // Save to database, send email, etc.
    return ['success' => true];
});

// Register shortcode
$shortcode->registerShortcode('contact_form');
```

Use in content:

```
[contact_form]
[contact_form wrapper="custom-class"]

```

See `SHORTCODES_GUIDE.md` for complete documentation and examples.

Documentation
-------------

[](#documentation)

- **[QUICKSTART.md](QUICKSTART.md)** - 5-minute quick start guide
- **[INTEGRATION\_GUIDE.md](INTEGRATION_GUIDE.md)** - Detailed integration instructions for Core PHP and Laravel
- **[API\_REFERENCE.md](API_REFERENCE.md)** - Complete API reference
- **[SHORTCODES\_GUIDE.md](SHORTCODES_GUIDE.md)** - Shortcode system documentation
- **[examples/](examples/)** - Working examples for all features

License
-------

[](#license)

MIT License - see LICENSE file for details

Support
-------

[](#support)

For issues, questions, or contributions, please visit the repository.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance65

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

212d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/13fcb3d03e44ad1b347e8ee794784877310260fdc4f7500bc155ce7c8628e1a2?d=identicon)[TaranpreetSinghRayat](/maintainers/TaranpreetSinghRayat)

---

Top Contributors

[![TaranpreetSinghRayat](https://avatars.githubusercontent.com/u/17387455?v=4)](https://github.com/TaranpreetSinghRayat "TaranpreetSinghRayat (15 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tweekersnut-forms-lib/health.svg)

```
[![Health](https://phpackages.com/badges/tweekersnut-forms-lib/health.svg)](https://phpackages.com/packages/tweekersnut-forms-lib)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
