PHPackages                             sglusnevs/violin - 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. sglusnevs/violin

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

sglusnevs/violin
================

Violin is an easy to use, highly customisable PHP validator.

2.2.3(5y ago)0811MITPHPPHP &gt;=7.2

Since Jan 12Pushed 5y agoCompare

[ Source](https://github.com/sglusnevs/violin)[ Packagist](https://packagist.org/packages/sglusnevs/violin)[ Docs](https://github.com/sglusnevs/violin)[ RSS](/packages/sglusnevs-violin/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (11)Used By (0)

Violin
======

[](#violin)

[![Build Status](https://camo.githubusercontent.com/ea9f116df27d312fabb0f72a01a28e2c22639af117b6d1c1c13b80395426d420/68747470733a2f2f7472617669732d63692e6f72672f616c6578676172726574742f76696f6c696e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/alexgarrett/violin) [![Gitter](https://camo.githubusercontent.com/abe08b740a4156153736f791393ec4da6619c4be73212e75769f52edacc0e2b5/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667)](https://gitter.im/alexgarrett/violin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

Violin is an easy to use, highly customisable PHP validator.

**Note: This package is under heavy development and is not recommended for production.**

Installing
----------

[](#installing)

Install using Composer.

```
{
    "require": {
        "alexgarrett/violin": "2.*"
    }
}
```

Basic usage
-----------

[](#basic-usage)

```
use Violin\Violin;

$v = new Violin;

$v->validate([
    'name'  => ['billy', 'required'],
    'age'   => [20, 'required|int']
]);

if($v->passes()) {
    echo 'Validation passed, woo!';
} else {
    echo '', var_dump($v->errors()->all()), '';
}
```

Adding custom rules
-------------------

[](#adding-custom-rules)

Adding custom rules is simple. If the closure returns false, the rule fails.

```
$v->addRuleMessage('isbanana', 'The {field} field expects "banana", found "{value}" instead.');

$v->addRule('isbanana', function($value, $input, $args) {
    return $value === 'banana';
});

$v->validate([
    'fruit' => ['apple', 'isbanana']
]);
```

Adding custom error messages
----------------------------

[](#adding-custom-error-messages)

You can add rule messages, or field messages for total flexibility.

### Adding a rule message

[](#adding-a-rule-message)

```
$v->addRuleMessage('required', 'You better fill in the {field} field, or else.');
```

### Adding rule messages in bulk

[](#adding-rule-messages-in-bulk)

```
$v->addRuleMessages([
    'required' => 'You better fill in the {field} field, or else.',
    'int'      => 'The {field} needs to be an integer, but I found {value}.',
]);
```

### Adding a field message

[](#adding-a-field-message)

Any field messages you add are used before any default or custom rule messages.

```
$v->addFieldMessage('username', 'required', 'You need to enter a username to sign up.');
```

### Adding field messages in bulk

[](#adding-field-messages-in-bulk)

```
$v->addFieldMessages([
    'username' => [
        'required' => 'You need to enter a username to sign up.'
    ],
    'age' => [
        'required' => 'I need your age.',
        'int'      => 'Your age needs to be an integer.',
    ]
]);
```

### Using Field Aliases

[](#using-field-aliases)

Field Aliases helps you format any error messages without showing weird form names or the need to create a custom error.

```
$v->validate([
    'username_box|Username' => ['' => 'required']
]);

// Error output: "Username is required."
```

### Callbacks

[](#callbacks)

Violin allows you to attach callbacks to be run **before** or **after** any validation. This might be useful if you need to do some further validation, or maybe raise an event. You can add as many **before** and **after** callbacks as you want, and you can also use the current Violin instance within them.

Examples:

```
$v->before(function($violin) {
    // This will happen before the validation..
});
```

```
$v->after(function($violin) {
    // This will happen after the validation..
});
```

### Extending Violin

[](#extending-violin)

You can extend the Violin class to add custom rules, rule messages and field messages. This way, you can keep a tidy class to handle custom validation if you have any dependencies, like a database connection or language files.

```
class MyValidator extends Violin
{
    protected $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;

        // Add rule message for custom rule method.
        $this->addRuleMessage('uniqueUsername', 'That username is taken.');
    }

    // Custom rule method for checking a unique username in our database.
    // Just prepend custom rules with validate_
    public function validate_uniqueUsername($value, $input, $args)
    {
        $user = $this->db->prepare("
            SELECT count(*) as count
            FROM users
            WHERE username = :username
        ");

        $user->execute(['username' => $value]);

        if($user->fetchObject()->count) {
            return false; // Username exists, so return false.
        }

        return true;
    }
}

// A database connection.
$db = new PDO('mysql:host=127.0.0.1;dbname=website', 'root', 'root');

// Instantiate your custom class with dependencies.
$v = new MyValidator($db);

$v->validate([
    'username' => ['billy', 'required|uniqueUsername']
]);
```

Rules
-----

[](#rules)

This list of rules are **in progress**. Of course, you can always contribute to the project if you'd like to add more to the base ruleset.

#### alnum

[](#alnum)

If the value is alphanumeric.

#### alnumDash

[](#alnumdash)

If the value is alphanumeric. Dashes and underscores are permitted.

#### alpha

[](#alpha)

If the value is alphabetic letters only.

#### array

[](#array)

If the value is an array.

#### between(int, int)

[](#betweenint-int)

Checks if the value is within the intervals defined. This check is inclusive, so 5 is between 5 and 10.

#### bool

[](#bool)

If the value is a boolean.

#### email

[](#email)

If the value is a valid email.

#### int

[](#int)

If the value is an integer, including numbers within strings. 1 and '1' are both classed as integers.

#### number

[](#number)

If the value is a number, including numbers within strings.

> Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.

#### ip

[](#ip)

If the value is a valid IP address.

#### min(int, \[number\])

[](#minint-number)

Check if string length is greater than or equal to given `int`. To check the size of a number, pass the optional `number` option.

```
$v->validate([
    'username' => ['billy', 'required|min(3)|max(20)'],
    'age' => ['20', 'required|min(18, number)|max(100, number)']
]);
```

#### max(int, \[number\])

[](#maxint-number)

Check if string length is less than or equal to given `int`. To check the size of a number, pass the optional `number` option.

#### required

[](#required)

If the value is present.

#### url

[](#url)

If the value is formatted as a valid URL.

#### matches(field)

[](#matchesfield)

Checks if one given input matches the other. For example, checking if *password* matches *password\_confirm*.

#### date

[](#date)

If the given input is a valid date.

You can validate human readable dates like '25th October 1961' and instances of `DateTime`. For example:

```
$twoDaysAgo = new DateTime('2 days ago');
$date = $twoDaysAgo->format('d M Y');

$v->validate([
    'date' => [$date, 'required|date']
]);
```

#### checked

[](#checked)

If a field has been 'checked' or not, meaning it contains one of the following values: *'yes'*, *'on'*, *'1'*, *1*, *true*, or *'true'*. This can be used for determining if an HTML checkbox has been checked.

#### regex(expression)

[](#regexexpression)

If the given input has a match for the regular expression given.

Contributing
------------

[](#contributing)

Please file issues under GitHub, or submit a pull request if you'd like to directly contribute.

### Running tests

[](#running-tests)

Tests are run with phpunit. Run `./vendor/bin/phpunit` to run tests.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 68.8% 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

Every ~219 days

Recently: every ~472 days

Total

10

Last Release

2172d ago

Major Versions

1.1.1 → 2.0.02015-03-26

PHP version history (2 changes)2.2.0PHP &gt;=5.4

2.2.3PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/711f223fc7dae97d5dc25bb3b6d406cce3ed786df113b177ffd463d551cf8e0b?d=identicon)[sglusnevs](/maintainers/sglusnevs)

---

Top Contributors

[![oxyzero](https://avatars.githubusercontent.com/u/40165401?v=4)](https://github.com/oxyzero "oxyzero (22 commits)")[![kezadias](https://avatars.githubusercontent.com/u/5727111?v=4)](https://github.com/kezadias "kezadias (8 commits)")[![matiit](https://avatars.githubusercontent.com/u/138194?v=4)](https://github.com/matiit "matiit (2 commits)")

---

Tags

validation

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/sglusnevs-violin/health.svg)

```
[![Health](https://phpackages.com/badges/sglusnevs-violin/health.svg)](https://phpackages.com/packages/sglusnevs-violin)
```

###  Alternatives

[composer/semver

Version comparison library that offers utilities, version constraint parsing and validation.

3.3k489.6M672](/packages/composer-semver)[giggsey/libphonenumber-for-php

A library for parsing, formatting, storing and validating international phone numbers, a PHP Port of Google's libphonenumber.

5.0k148.7M416](/packages/giggsey-libphonenumber-for-php)[respect/validation

The most awesome validation engine ever created for PHP

5.9k37.4M383](/packages/respect-validation)[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M107](/packages/propaganistas-laravel-phone)[opis/json-schema

Json Schema Validator for PHP

64236.9M186](/packages/opis-json-schema)[giggsey/libphonenumber-for-php-lite

A lite version of giggsey/libphonenumber-for-php, which is a PHP Port of Google's libphonenumber

8412.9M47](/packages/giggsey-libphonenumber-for-php-lite)

PHPackages © 2026

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