simtabi/enekia

Additional validation rules for the Laravel framework

dev-master 2022-05-23 21:23 UTC

This package is auto-updated.

Last update: 2022-06-23 21:28:36 UTC


README

Enekia is data validation library for Laravel's own validation system. The package adds rules to validate data like IBAN, BIC, ISBN, creditcard numbers and more.

Installation

You can install this package quick and easy with Composer.

Require the package via Composer:

$ composer require simtabi/enekia

Laravel integration

The Validation library is built to work with the Laravel Framework (>=7). It comes with a service provider, which will be discovered automatically and registers the validation rules into your installation. The package provides 30 additional validation rules including error messages.

use Illuminate\Support\Facades\Validator;
use Simtabi\Enekia\Laravel\Rules\CreditCard\CardNumberBasic;
use Simtabi\Enekia\Laravel\Rules\HexColor;
use Simtabi\Enekia\Laravel\Rules\Username;
use Enekia\EnekiaLaravelValidator;

$validator = EnekiaLaravelValidator::make($request->all(), [
    'color' => new Hexcolor(3), // pass rule as object
    'name' => ['required', 'min:3', 'max:20', new Username()], // combining rules works as well
]);

Make sure to pass any of the additional validation rules as objects and not as strings.

Changing the error messages:

Add the corresponding key to /resources/lang/<language>/validation.php like this:

// example
'iban' => 'Please enter IBAN number!',

Or add your custom messages directly to the validator like described in the docs.

Standalone usage

It is also possible to use this library without the Laravel framework. You won't have the Laravel facades available, so make sure to use Simtabi\Enekia\Validator for your calls.

use Simtabi\Enekia\EnekiaLaravelValidator;
use Simtabi\Enekia\Laravel\Rules\CardNumberBasic;
use Simtabi\Enekia\Exceptions\ValidationException;

// use static factory method to create laravel validator
$validator = EnekiaLaravelValidator::make($request->all(), [
    'ccnumber' => new CardNumberBasic(),
    'iban' => ['required', new Iban()],
]);

// validate single values by calling static methods
$result = EnekiaLaravelValidator::isHexcolor('foobar'); // false
$result = EnekiaLaravelValidator::isHexcolor('#ccc'); // true
$result = EnekiaLaravelValidator::isBic('foo'); // false

// assert single values
try {
    EnekiaLaravelValidator::assertHexcolor('foobar');
} catch (ValidationException $e) {
    $message = $e->getMessage();
}

Available Rules

The following validation rules are available with this package.

Base64 encoded string

The field under validation must be Base64 encoded.

public Simtabi\Enekia\Laravel\Rules\Base64::__construct()

Business Identifier Code (BIC)

Checks for a valid Business Identifier Code (BIC).

public Simtabi\Enekia\Laravel\Rules\Bic::__construct()

Camel case string

The field under validation must be a formated in Camel case.

public Simtabi\Enekia\Laravel\Rules\Camelcase::__construct()

Classless Inter-Domain Routing (CIDR)

Check if the value is a Classless Inter-Domain Routing notation (CIDR).

public Simtabi\Enekia\Laravel\Rules\Cidr::__construct()

CardNumberBasic

The field under validation must be a valid creditcard number.

public Simtabi\Enekia\Laravel\Rules\CreditCard\CardNumberBasic::__construct()

Data URI scheme

The field under validation must be a valid Data URI.

public Simtabi\Enekia\Laravel\Rules\DataUri::__construct()

Domain name

The field under validation must be a well formed domainname.

public Simtabi\Enekia\Laravel\Rules\Domainname::__construct()

European Article Number (EAN)

Checks for a valid European Article Number.

public Simtabi\Enekia\Laravel\Rules\Ean::__construct(?int $length = null)

Parameters

length

Optional integer length (8 or 13) to check only for EAN-8 or EAN-13.

Global Trade Item Number (GTIN)

Checks for a valid Global Trade Item Number.

public Simtabi\Enekia\Laravel\Rules\Gtin::__construct(?int $length = null)

Parameters

length

Optional integer length to check only for certain types (GTIN-8, GTIN-12, GTIN-13 or GTIN-14).

Hexadecimal color code

The field under validation must be a valid hexadecimal color code.

public Simtabi\Enekia\Laravel\Rules\HexColor::__construct(?int $length = null)

Parameters

length

Optional length as integer to check only for shorthand (3 characters) or full hexadecimal (6 characters) form.

Text without HTML

The field under validation must be free of any html code.

public Simtabi\Enekia\Laravel\Rules\HtmlClean::__construct()

International Bank Account Number (IBAN)

Checks for a valid International Bank Account Number (IBAN).

public Simtabi\Enekia\Laravel\Rules\Iban::__construct()

International Mobile Equipment Identity (IMEI)

The field under validation must be a International Mobile Equipment Identity (IMEI).

public Simtabi\Enekia\Laravel\Rules\Imei::__construct()

International Standard Book Number (ISBN)

The field under validation must be a valid International Standard Book Number (ISBN).

public Simtabi\Enekia\Laravel\Rules\Isbn::__construct(?int $length = null)

Parameters

length

Optional length parameter as integer to check only for ISBN-10 or ISBN-13.

International Securities Identification Number (ISIN)

Checks for a valid International Securities Identification Number (ISIN).

public Simtabi\Enekia\Laravel\Rules\Isin::__construct()

International Standard Serial Number (ISSN)

Checks for a valid International Standard Serial Number (ISSN).

public Simtabi\Enekia\Laravel\Rules\Issn::__construct()

JSON Web Token (JWT)

The given value must be a in format of a JSON Web Token.

public Simtabi\Enekia\Laravel\Rules\Jwt::__construct()

Kebab case string

The given value must be formated in Kebab case.

public Simtabi\Enekia\Laravel\Rules\Kebabcase::__construct()

Lower case string

The given value must be all lower case letters.

public Simtabi\Enekia\Laravel\Rules\Lowercase::__construct()

Luhn algorithm

The given value must verify against its included Luhn algorithm check digit.

public Simtabi\Enekia\Laravel\Rules\Luhn::__construct()

MAC address

The field under validation must be a media access control address (MAC address).

public Simtabi\Enekia\Laravel\Rules\MacAddress::__construct()

Media (MIME) type

Checks for a valid Mime Type (Media type).

public Simtabi\Enekia\Laravel\Rules\MimeType::__construct()

Postal Code

The field under validation must be a postal code of the given country.

public Simtabi\Enekia\Laravel\Rules\Postalcode::__construct(string $countrycode)

Parameters

countrycode

Country code in ISO-639-1 format.

Postal Code (static instantiation)

public static Simtabi\Enekia\Laravel\Rules\Postalcode::countrycode(string $countrycode): Postalcode

Parameters

countrycode

Country code in ISO-639-1 format.

Postal Code (static instantiation with callback)

public static Simtabi\Enekia\Laravel\Rules\Postalcode::resolve(callable $callback): Postalcode

Parameters

callback

Callback to resolve ISO-639-1 country code from other source.

Postal Code (static instantiation with reference)

public static Simtabi\Enekia\Laravel\Rules\Postalcode::reference(string $reference): Postalcode

Parameters

reference

Reference key to get ISO-639-1 country code from other data in validator.

Semantic Version Number

The field under validation must be a valid version numbers using Semantic Versioning.

public Simtabi\Enekia\Laravel\Rules\SemVer::__construct()

SEO-friendly short text (Slug)

The field under validation must be a user- and SEO-friendly short text.

public Simtabi\Enekia\Laravel\Rules\Slug::__construct()

Snake case string

The field under validation must formated as Snake case text.

public Simtabi\Enekia\Laravel\Rules\Snakecase::__construct()

Title case string

The field under validation must formated in Title case.

public Simtabi\Enekia\Laravel\Rules\Titlecase::__construct()

Universally Unique Lexicographically Sortable Identifier (ULID)

The field under validation must be a valid Universally Unique Lexicographically Sortable Identifier.

public Simtabi\Enekia\Laravel\Rules\Ulid::__construct()

Upper case string

The field under validation must be all upper case.

public Simtabi\Enekia\Laravel\Rules\Uppercase::__construct()

Username

The field under validation must be a valid username. Consisting of alpha-numeric characters, underscores, minus and starting with a alphabetic character. Multiple underscore and minus chars are not allowed. Underscore and minus chars are not allowed at the beginning or end.

public Simtabi\Enekia\Laravel\Rules\Username::__construct()

LocationCoordinates

Requires that the given value is a comma-separated set of latitude and longitude coordinates

public Simtabi\Enekia\Laravel\Rules\Localization\LocationCoordinates::__construct()

EncodedImage

Requires that the given value is a base64-encoded image of a given mime types - see class for details

public Simtabi\Enekia\Laravel\Rules\EncodedImage::__construct()

CitizenshipIdentificationNumber

Requires that the given value is a base64-encoded image of a given mime types - see class for details

public Simtabi\Enekia\Laravel\Rules\CitizenshipIdentificationNumber::__construct()

OddNumber

Requires that the given value is an odd number (decimals are first converted using intval)

public Simtabi\Enekia\Laravel\Rules\OddNumber::__construct()

EvenNumber

Requires that the given value is an even number (decimals are first converted using intval)

public Simtabi\Enekia\Laravel\Rules\EvenNumber::__construct()

FileExists

Requires that the given value is a path to an existing file - see class for details

public Simtabi\Enekia\Laravel\Rules\FileExists::__construct()

DisposableEmail

Requires the presence of an email address which is not disposable. By default, if the API fails to load, the email will be accepted. However, you can override this by adding a boolean parameter e.g. new DisposableEmail(true).

public Simtabi\Enekia\Laravel\Rules\DisposableEmail::__construct()

Decimal

Requires that the given value is a decimal with an appropriate format - see class for details

public Simtabi\Enekia\Laravel\Rules\Decimal::__construct()

Equals

Requires that the given value is equal to another given value

public Simtabi\Enekia\Laravel\Rules\Equals::__construct()

EndsWith

Requires that the given value ends with a given string - see class for details

public Simtabi\Enekia\Laravel\Rules\EndsWith::__construct()

NoWhitespace

Requires that the given value not include any whitespace characters

public Simtabi\Enekia\Laravel\Rules\NoWhitespace::__construct()

DoesNotExist

Requires that the given value is not present in a given database table / column - see class for details

public Simtabi\Enekia\Laravel\Rules\DoesNotExist::__construct()

CurrencySymbol

Requires the presence of a monetary figure e.g $72.33 - see class for details

public Simtabi\Enekia\Laravel\Rules\CurrencySymbol::__construct()

Domain

Requires that the given value be a domain e.g. google.com, www.google.com

public Simtabi\Enekia\Laravel\Rules\Domain::__construct()

MaxWords

Requires that the given value cannot contain more words than specified

public Simtabi\Enekia\Laravel\Rules\MaxWords::__construct()

ExcludesHtml

Requires that the given value doesn't contain Html tags

public Simtabi\Enekia\Laravel\Rules\ExcludesHtml::__construct()

IncludesHtml

Requires that the given value contains Html tags

public Simtabi\Enekia\Laravel\Rules\IncludesHtml::__construct()

StringContains

Requires that the given value contains the given values

public Simtabi\Enekia\Laravel\Rules\StringContains::__construct()

Base64EncodedString

Requires that the given value is a base64 encoded string

public Simtabi\Enekia\Laravel\Rules\Base64EncodedString::__construct()

Coordinate

Requires that the given value has valid coordinates

public Simtabi\Enekia\Laravel\Rules\Coordinate::__construct()

DomainRestrictedEmail

Requires that the given value is a valid domain restricted email

public Simtabi\Enekia\Laravel\Rules\DomainRestrictedEmail::__construct()

HexColourCode

Requires that the given value is a valid hex color code

public Simtabi\Enekia\Laravel\Rules\HexColourCode::__construct()

NumberParity

Requires that the given value has valid parity

public Simtabi\Enekia\Laravel\Rules\NumberParity::__construct()

Salutation

Requires that the given value is a valid salutation

public Simtabi\Enekia\Laravel\Rules\Salutation::__construct()

VatNumber

Requires that the given value is a valid VAT number

public Simtabi\Enekia\Laravel\Rules\VatNumber::__construct()

Contains

Requires that the given value contains a given value

public Simtabi\Enekia\Laravel\Rules\Contains::__construct()

DateAfterOrEqual

Requires that the given value is a date and it's after or equal

public Simtabi\Enekia\Laravel\Rules\DateAfterOrEqual::__construct()

DateBeforeOrEqual

Requires that the given value is a date and it's before or equal

public Simtabi\Enekia\Laravel\Rules\DateBeforeOrEqual::__construct()

DateHasSpecificMinutes

Requires that the given value is a date and has specific minutes

public Simtabi\Enekia\Laravel\Rules\DateHasSpecificMinutes::__construct()

Hostname

Requires that the given value is a valid hostname i.e google.com

public Simtabi\Enekia\Laravel\Rules\Hostname::__construct()

Interval

Requires that the given value is a valid interval, i.e. PT30S.

public Simtabi\Enekia\Laravel\Rules\Interval::__construct()

MaximumHourDifference

Requires that the given value has a maximum hour difference

public Simtabi\Enekia\Laravel\Rules\MaximumHourDifference::__construct()

NotContains

Requires that the given value does not contain a given value

public Simtabi\Enekia\Laravel\Rules\NotContains::__construct()

NotEndsWith

Requires that the given value does not end with a given value

public Simtabi\Enekia\Laravel\Rules\NotEndsWith::__construct()

NotStartsWith

Requires that the given value does not start with a given value

public Simtabi\Enekia\Laravel\Rules\NotStartsWith::__construct()

PositiveInterval

Requires that the given value is a positive interval

public Simtabi\Enekia\Laravel\Rules\PositiveInterval::__construct()

Price

Requires that the given value is a valid price

public Simtabi\Enekia\Laravel\Rules\Price::__construct()

SecureUrl

Requires that the given value is a valid secure url

public Simtabi\Enekia\Laravel\Rules\SecureUrl::__construct()

Phone

Requires that the given value is a valid phone number

public Simtabi\Enekia\Laravel\Rules\Phone::__construct()

PostalCodeDutch

Requires that the given value is a valid dutch postal code

public Simtabi\Enekia\Laravel\Rules\PostalCodeDutch::__construct()

Timezone

Requires that the given value is a valid timezone

public Simtabi\Enekia\Laravel\Rules\Localization\Timezone::__construct()

Language

Requires that the given value is a valid language using iso codes, nd or names

public Simtabi\Enekia\Laravel\Rules\Localization\Language::__construct()

IP Address

Validates an ip address is either public or private. Supports ipv4 & ipv6.

Usage

Validate an ip address is a public address.

use Simtabi\Enekia\Laravel\Rules\IpAddress;

$request->validate([
    'ip' => ['required', new PublicIpAddress],
]);

Validate an ip address is a private address.

use Simtabi\Enekia\Laravel\Rules\IpAddress;

$request->validate([
    'ip' => ['required', new PrivateIpAddress],
]);

Subdomain

Usage

use Simtabi\Enekia\Laravel\Rules\Subdomain;

$request->validate([
    'domain' => ['required', new Subdomain],
]);

IsOffensiveWord

Usage

The following code snippet shows an example of how to use the offensive validation rule.

use Simtabi\Enekia\Laravel\Rules\IsOffensiveWord;

$request->validate([
    'username' => ['required', new Offensive],
]);

IsAStateInNorthAmerica

Usage

The following code snippet shows an example of how to use the north america state validation rule.

use Simtabi\Enekia\Laravel\Rules\Localization\IsAStateInNorthAmerica;

$request->validate([
    'state' => ['required', new IsAStateInNorthAmerica('US')->doAbbreviatedName()],
]);

ModelsExists

ModelsExists

Usage

Determine if all of the values in the input array exist as attributes for the given model class.

By default the rule assumes that you want to validate using id attribute. In the example below the validation will pass if all model_ids exist for the Model.

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\ModelsExists;

public function rules()
{
    return [
        'model_ids' => ['array', new ModelsExists(Model::class)],
    ];
}

You can also pass an attribute name as the second argument. In the example below the validation will pass if there are users for each email given in the user_emails of the request.

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\ModelsExists;

public function rules()
{
    return [
        'user_emails' => ['array', new ModelsExists(User::class, 'emails')],
    ];
}

Authorized

Authorized

Determine if the user is authorized to perform an ability on an instance of the given model. The id of the model is the field under validation

Consider the following policy:

class ModelPolicy
{
    use HandlesAuthorization;

    public function edit(User $user, Model $model): bool
    {
        return $model->user->id === $user->id;
    }
}

This validation rule will pass if the id of the logged in user matches the user_id on TestModel who's it is in the model_id key of the request.

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Authorized;

public function rules()
{
    return [
        'model_id' => [new Authorized('edit', TestModel::class)],
    ];
}

Optionally, you can provide an authentication guard as the third parameter.

new Authorized('edit', TestModel::class, 'guard-name')

Model resolution

If you have implemented the getRouteKeyName method in your model, it will be used to resolve the model instance. For further information see Customizing The Default Key Name

Country

Country

Determine if the field under validation is a valid 2 letter ISO3166 country code (example of valid country codes: GB, DK, NL).

Note that this rule require the package league/iso3166 to be installed: composer require league/iso3166

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Localization\Country;

public function rules()
{
    return [
        'country_code' => ['required', new Country()->doIso2()],
    ];
}

If you want to validate a nullable country code field, you can call the nullable() method on the CountryCode rule. This way null and 0 are also passing values:

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Localization\Country;

public function rules()
{
    return [
        'country_code' => [(new Country())->doIso2()->nullable()],
    ];
}

Enum

This rule will validate if the value under validation is part of the given enum class. We assume that the enum class has a static toArray method that returns all valid values. If you're looking for a good enum class, take a look at spatie/enum or myclabs/php-enum.

Consider the following enum class:

class UserRole extends MyCLabs\Enum\Enum
{
    const ADMIN = 'admin';
    const REVIEWER = 'reviewer';
}

The Enum rule can be used like this:

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Enum;

public function rules()
{
    return [
        'role' => [new Enum(UserRole::class)],
    ];
}

CurrencyCode

Usage — still WIP

Determine if the field under validation is a valid 3 letter ISO4217 currency code (example of valid currencies: EUR, USD, CAD).

Note that this rule require the package league/iso3166 to be installed: composer require league/iso3166

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Currency;

public function rules()
{
    return [
        'currency' => ['required', new Currency()->doNumericCode()], // Must be present and a valid currency
    ];
}

If you want to validate a nullable currency field, simple do not let it be required as described in the Laravel Docs for implicit validation rules:

... when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Currency;

public function rules()
{
    return [
        'currency' => [new Currency()->doNumericCode()], // This will pass for any valid currency, an empty value or null
    ];
}

Delimited

This rule can validate a string containing delimited values. The constructor accepts a rule that is used to validate all separate values.

Here's an example where we are going to validate a string containing comma separated email addresses.

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email')],
    ];
}

Here's some example input that passes this rule:

  • 'sebastian@example.com, alex@example.com'
  • ''
  • 'sebastian@example.com'
  • 'sebastian@example.com, alex@example.com, brent@example.com'
  • ' sebastian@example.com , alex@example.com , brent@example.com '

This input will not pass:

  • '@example.com'
  • 'nocomma@example.com nocommatoo@example.com'
  • 'valid@example.com, invalid@'

Setting a minimum

You can set minimum amout of items that should be present:

(new Delimited('email'))->min(2)
  • 'sebastian@example.com, alex@example.com' // passes
  • 'sebastian@example.com' // fails

Setting a maximum

(new Delimited('email'))->max(2)
  • 'sebastian@example.com' // passes
  • 'sebastian@example.com, alex@example.com, brent@example.com' // fails

Allowing duplicate items

By default the rule will fail if there are duplicate items found.

  • 'sebastian@example.com, sebastian@example.com' // fails

You can allowing duplicate items like this:

(new Delimited('numeric'))->allowDuplicates()

Now this will pass: 1,1,2,2,3,3

Customizing the separator

(new Delimited('email'))->separatedBy(';')
  • 'sebastian@example.com; alex@example.com; brent@example.com' // passes
  • 'sebastian@example.com, alex@example.com, brent@example.com' // fails

Skip trimming of items

(new Delimited('email'))->doNotTrimItems()
  • 'sebastian@example.com,freek@example.com' // passes
  • 'sebastian@example.com, freek@example.com' // fails
  • 'sebastian@example.com , freek@example.com' // fails

Composite rules

The constructor of the validator accepts a validation rule string, a validate instance, or an array.

new Delimited('email|max:20')
  • 'short@example.com' // passes
  • 'invalid' // fails
  • 'loooooooonnnggg@example.com' // fails

Passing custom error messages

The constructor of the validator accepts a custom error messages array as second parameter.

// in a `FormRequest`

use Simtabi\Enekia\Laravel\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email', $this->messages())],
    ];
}

public function messages()
{
    return [
        'emails.email' => 'Not all the given e-mails are valid.',
    ];
}

Custom word lists

If the defaults are too strict (or not strict enough), you can optionally specify a custom list of offensive words and custom whitelist. Below is an example of using a custom blacklist and whitelist.

use Simtabi\Enekia\Laravel\Rules\IsOffensiveWord;
use Simtabi\Enekia\Helpers\OffensiveWordChecker;

$blacklist = ['moist', 'stinky', 'poo'];
$whitelist = ['poop'];

$request->validate([
    'username' => ['required', new Offensive(new OffensiveWordChecker($blacklist, $whitelist))],
]);

Available Rules

BicNumber

Validates the provided BIC number.

Contains

Validates if the value contains a certain phrase.

'field' => [new Contains($needle)],

DateAfterOrEqual

Validates if the value is a date after or equals the provided date (Carbon).

'field' => [new DateAfterOrEqual($date)],

DateBeforeOrEqual

Validates if the value is a date before or equals the provided date (Carbon).

'field' => [new DateBeforeOrEqual($date)],

DateHasSpecificMinutes

Validates if the selected minutes for the provided date are according to the available minutes.

'field' => [new DateHasSpecificMinutes([0, 15, 30, 45])],

When the date is not according to the 'Y-m-d H:i' format then you are able to specify the format as second parameter:

'field' => [new DateHasSpecificMinutes([0, 15, 30, 45], 'd-m-Y H:i')],

DutchPhone

Validates if the value is a valid dutch phone number. Both mobile or landlines are supported. See the Phone validation rule to validate a phone number which isn't limited to the Netherlands.

PostalCodeDutch

Validates if the value is a valid dutch zip code, like 1234AB.

HexColor

Validates if the value contains a hex color, like #000000.

HostName

Validates if the value contains a valid hostname, like example.com.

InternationalBankAccountNumber

Validates if the value contains a valid IBAN.

Interval

Validates if the value is an interval, i.e. PT30S.

MaximumHourDifference

Validates if the value is differing less then the provided amount of hours.

'field' => [new MaximumHourDifference($start, 10)];

Mime Type

Validates if the value is valid MIME.

NotContains

Validates if the value NOT contains a certain phrase.

'field' => [new NotContains($needle)],

NotEndsWith

Validates if the value NOT ends with a certain phrase.

'field' => [new NotEndsWith($needle)],

NotStartsWith

Validates if the value NOT starts with a certain phrase.

'field' => [new NotEndsWith($needle)],

Password strength

Validates if the value contains at least a letter, a capital and a number.

Phone

Validates if the value is a valid phone number.

Positive interval

Validates if the value is an interval and the interval is positive.

Price

Validates if the value is a valid price. The rule optionally accepts a specific decimal sign. When the decimal isn't provided it accepts both , or . signs.

'field' => [new Price()], // accepts both , and .
'field' => [new Price(',')], // accepts only ,

Secure url

Validates if the value is a valid secure url, i.e. is a HTTPS url.

Semver

Validates if the value is a valid version according to the Semver standard.

VatNumber

Validates if the value is a valid formatted VAT number.

Be aware: It doesn't check if the number is known in the VAT database. If you need to know the VAT number is truly legit, I'm currently offering an easy to use (paid) service for that.

Usage

As discussed in the official Laravel documentation, import the required rule whenever required:

use Simtabi\Enekia\Laravel\Rules\TitleCase;

// ...

$request->validate([
    'team' => ['required', new TitleCase()],
]);

Alternatively use the rule directly with a Laravel form request object

Available rules

Base64EncodedString

Ensure the passed attribute is a valid base 64 encoded string.

Coordinate

Ensure the passed attribute is a valid comma separated Latitude and Longitude string. For example: 51.507877,-0.087732.

DomainRestrictedEmail

Ensure the passed email in question is part of the provided whitelist of domains.

For instance, to ensure the given email domain is f9web.co.uk or laravel.com:

use Simtabi\Enekia\Laravel\Rules\DomainRestrictedEmail;

// ...

$request->validate([
    'email' => [
        'required', 
        (new DomainRestrictedEmail())->validDomains([
            'f9web.co.uk',
            'laravel.com',
        ]),
    ],
]);

The validation message will include the list of whitelisted domains based upon the provided configuration.

ExcludesHtml

Ensure the passed attribute does not contain HTML.

HexColourCode

Ensure the passed attribute is a valid hex colour code (three of six characters in length), optionally validating the presence of the # prefix.

Minimum usage example to validate a short length code with the prefix i.e. #fff:

use Simtabi\Enekia\Laravel\Rules\HexColourCode;

(new HexColourCode());

Extended usage example to validate a long length code , omitting prefix i.e. cc0000:

use Simtabi\Enekia\Laravel\Rules\HexColourCode;

(new HexColourCode())->withoutHexPrefix()->longFormatHexCode();

Honorific

Ensure the passed attribute is a valid honorific, omitting appended dots. The list of valid honorifics is available here.

IncludesHtml

Ensure the passed attribute contains HTML.

NoWhitespace

Ensure the passed attribute contains no whitespace.

NumberParity

Validate the number parity.

An odd number:

use Simtabi\Enekia\Laravel\Rules\NumberParity;

// ...

$request->validate([
    'amount' => [
        'required', 
        (new NumberParity())->odd(),
    ],
]);

An even number:

use Simtabi\Enekia\Laravel\Rules\NumberParity;

// ...

$request->validate([
    'amount' => [
        'required', 
        (new NumberParity())->even(),
    ],
]);

StringContains

Ensure the given attribute contains the provided strings.

Minimum usage example to ensure the attribute in question contains the string php or laravel:

use Simtabi\Enekia\Laravel\Rules\StringContains;

// ...

$request->validate([
    'description' => [
        'required', 
        (new StringContains())->phrases([
            'laravel',
            'php',
        ]),
    ],
]);

Optionally force the string to contain all provided phrases:

use Simtabi\Enekia\Laravel\Rules\StringContains;

// ...

$request->validate([
    'description' => [
        'required', 
        (new StringContains())->phrases([
            'laravel',
            'php',
        ])->strictly(),
    ],
]);

The validation message will include the list phrases based upon the provided configuration.

StrongPassword

Ensure the given attribute matches the provided conditions.

Minimum usage example to ensure the attribute:

  • is a minimum of eight characters in length
  • contains upper and lowercase characters
  • contains at least one number
use Simtabi\Enekia\Laravel\Rules\Password\StrongPassword;

// ...

$request->validate([
    'password' => [
        'required', 
        (new StrongPassword()),
    ],
]);

Additional methods are available.

use Simtabi\Enekia\Laravel\Rules\Password\StrongPassword;

// ...

$request->validate([
    'password' => [
        'required', 
        (new StrongPassword())
            ->forceUppercaseCharacters()
            ->forceLowercaseCharacters(false)
            ->forceNumbers()
            ->forceSpecialCharacters()
            // ->withSpecialCharacters('£$*%^'),
    ],
]);

The default special characters are !@#$%^&*()\-_=+{};:,<."£~?|>. Optionally the withSpecialCharacters() method can be used to define a custom list.

TitleCase

Ensure the provided attribute is title case.

UKMobilePhone

Ensure the provided attribute is a valid UK mobile telephone number.

Uppercase

Ensure the provided attribute is entirely uppercase.

Credit Card validation

Usage

As FormRequest

<?php

namespace App\Http\Requests;

use Simtabi\Enekia\Laravel\Rules\CreditCard\CardCvc;
use Simtabi\Enekia\Laravel\Rules\CreditCard\CardNumber;
use Simtabi\Enekia\Laravel\Rules\CreditCard\CardExpirationYear;
use Simtabi\Enekia\Laravel\Rules\CreditCard\CardExpirationMonth;
use Illuminate\Foundation\Http\FormRequest;

class CreditCardRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'card_number' => ['required', new CardNumber],
            'expiration_year' => ['required', new CardExpirationYear($this->get('expiration_month'))],
            'expiration_month' => ['required', new CardExpirationMonth($this->get('expiration_year'))],
            'cvc' => ['required', new CardCvc($this->get('card_number'))]
        ];
    }
}

Card number

From request

$request->validate(
    ['card_number' => '37873449367100'],
    ['card_number' => new Simtabi\Enekia\Laravel\Rules\CreditCard\CardNumber]
);

Directly

(new Simtabi\Enekia\Laravel\Rules\CreditCard\Cards\Visa)
    ->setCardNumber('4012888888881881')
    ->isValidCardNumber()

Card expiration

From request

// CardExpirationYear requires card expiration month
$request->validate(
    ['expiration_year' => '2017'],
    ['expiration_year' => ['required', new Simtabi\Enekia\Laravel\Rules\CreditCard\CardExpirationYear($request->get('expiration_month'))]]
);

// CardExpirationMonth requires card expiration year
$request->validate(
    ['expiration_month' => '11'],
    ['expiration_month' => ['required', new Simtabi\Enekia\Laravel\Rules\CreditCard\CardExpirationMonth($request->get('expiration_year'))]]
);

// CardExpirationDate requires date format
$request->validate(
    ['expiration_date' => '02-18'],
    ['expiration_date' => ['required', new Simtabi\Enekia\Laravel\Rules\CreditCard\CardExpirationDate('MM-YY')]]
);

Directly

Simtabi\Enekia\Laravel\Rules\CreditCard\Cards\ExpirationDateValidator(
    $expiration_year,
    $expiration_month
)->isValid();

// Or static
Simtabi\Enekia\Laravel\Rules\CreditCard\Cards\ExpirationDateValidator::validate(
    $expiration_year,
    $expiration_month
);

Card CVC

From request

// CardCvc requires card number to determine allowed cvc length
$request->validate(
    ['cvc' => '123'],
    ['cvc' => new Simtabi\Enekia\Laravel\Rules\CreditCard\CardCvc($request->get('card_number'))]
);

Directly

Simtabi\Enekia\Laravel\Rules\CreditCard\Cards\Card::isValidCvcLength($cvc);

Contribution

Any ideas are welcome. Feel free to submit any issues or pull requests.

Testing

composer test

Security

If you discover any security related issues, please email imani@simtabi.com instead of using the issue tracker.

Credits & Inspiration

License

Enekia is licensed under the MIT License.