Giter Club home page Giter Club logo

axiom's Introduction

Axiom

This package provides a library of reusable validation rules for your Laravel projects. Use them to augment the existing set provided by Laravel itself.

Installation

Pull in the package using composer

composer require caneara/axiom

Upgrading

Axiom includes several breaking changes from the original package, so you'll need to follow these steps if you were using the old version:

  1. Ensure that you are using PHP 7.4 or later.
  2. Remove alphametric/laravel-validation-rules from your composer.json file.
  3. Run composer update to remove the package from your vendor directory.
  4. Install Axiom by running composer require caneara/axiom.
  5. Replace all instances of use Alphametric\Validation with use Axiom.
  6. The EndsWith rule has been removed as Laravel now natively supports this.
  7. The Equals rule has been removed. Instead, you should use Laravel's native in rule with a single option.
  8. The DoesNotExist rule has been renamed to Missing.

Usage

As per the Laravel documentation, simply import the relevant validation class wherever you require it, and then include it within the rules for a particular field:

use Axiom\Rules\StrongPassword;

// ...

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

IMPORTANT: As with all custom rules, you cannot use a pipe-delimited string. You must instead use an array e.g.

'password' => ['bail', 'required', new StrongPassword] // correct
'password' => 'bail|required|new StrongPassword'       // wrong

If the validation fails, the package will attempt to respond with a localized error message (see message keys below). If the key does not exist, it will fall back to a hard-coded English language version.

Available rules

The following validation rules are currently available:

Rule Message Key Description
StrongPassword validation.strong_password Requires the presence of a "strong" password - see class for details
TelephoneNumber validation.telephone_number Requires the presence of a valid telephone number - see class for details
RecordOwner validation.record_owner Requires the authenticated user's id to match the user_id column on a given database record e.g. owner:posts,id
MonetaryFigure validation.monetary_figure Requires the presence of a monetary figure e.g $72.33 - see class for details
DisposableEmail validation.disposable_email Requires the presence of an email address which is not disposable
Missing validation.missing Requires that the given value is not present in a given database table / column - see class for details
Decimal validation.decimal Requires that the given value is a decimal with an appropriate format - see class for details
EncodedImage validation.encoded_image Requires that the given value is a base64-encoded image of a given mime types - see class for details
LocationCoordinates validation.location_coordinates Requires that the given value is a comma-separated set of latitude and longitude coordinates
FileExists validation.file_exists Requires that the given value is a path to an existing file - see class for details
MacAddress validation.mac_address Requires that the given value is a valid MAC address
ISBN validation.isbn Requires that the given value is a valid ISBN-10 or ISBN-13 number
EvenNumber validation.even_number Requires that the given value is an even number (decimals are first converted using intval)
OddNumber validation.odd_number Requires that the given value is an odd number (decimals are first converted using intval)
Lowercase validation.lowercase Requires that the given value is a lower case string
Uppercase validation.uppercase Requires that the given value is a upper case string
Titlecase validation.titlecase Requires that the given value is a title case string
Domain validation.domain Requires that the given value be a domain e.g. google.com, www.google.com
CitizenIdentification validation.citizen_identification Requires that the given value be a citizen identification number of USA, UK, France, Brazil or Vietnam (see class for details)
WithoutWhitespace validation.without_whitespace Requires that the given value not include any whitespace characters
MaxWords validation.max_words Requires that the given value cannot contain more words than specified
HexColor validation.hex_color Requires that the given value is a valid hex color eg. #fff, #0f0f0f, #00ff0080

Contributing

Thank you for considering a contribution to Axiom. You are welcome to submit a PR containing improvements, however if they are substantial in nature, please also be sure to include a test or tests.

License

The MIT License (MIT). Please see License File for more information.

axiom's People

Contributors

andcl avatar dostrog avatar gemui avatar guiassemany avatar innoflash avatar j2teamnnl avatar mattkingshott avatar samuelchlui avatar tkayfun avatar tumainimosha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

axiom's Issues

Readme file should be updated with a note

I think readme file should be updated with a text like:

Please note that rule definition in validation array not work with single | delimited string as:

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

you have to use only array in validation definition like our code example.

someone still using sigle string in validation definition (like me in one project) and this can make confusion getting newStrongPassword don't exist error.

Validation rules missing during tests?

I'm trying to test for the validation.strong_password rule in my test, but none of the validation strings seem to be added to the validation array.

For instance, I have a test:

public function testSubmitPasswordResetPasswordTooShort()
    {
        $user = factory(User::class)->create([
            'password' => Hash::make(self::USER_ORIGINAL_PASSWORD),
        ]);

        $token = Password::broker()->createToken($user);

        $password = str_random(self::MIN_PASSWORD_LENGTH - 1);

        $this
            ->followingRedirects()
            ->from(route(self::ROUTE_PASSWORD_RESET, [
                'token' => $token,
            ]))
            ->post(route(self::ROUTE_PASSWORD_RESET_SUBMIT), [
                'token' => $token,
                'email' => $user->email,
                'password' => $password,
                'password_confirmation' => $password,
            ])
            ->assertSuccessful()
            ->assertSee(__('validation.strong_password', [
                'attribute' => 'password',
            ]));

        $user->refresh();

        $this->assertFalse(Hash::check($password, $user->password));

        $this->assertTrue(Hash::check(self::USER_ORIGINAL_PASSWORD,
            $user->password));
    }

but validation.strong_password doesn't return anything.

Should I manually add all the rules to my lang\en\validation.php?

Exists or 0

In selections, ID should be exists or 0 for roots!
For example in category, there is parent_id column, so, in root categories parent_id is 0.
I have been searching for such exists_or_zero validation method with no success.

Namespace error

When I install the package with composer:

composer require mattkingshott/axiom

I don't have problem, but when I try to import into project a rule it don't work.
I have noted that into vendor dir the namespaces is

namespace Alphametric\Validation\Rules;

see attached images of my editor.
I have already tried to remove and reinstall the package, dump-autoload in composer and refresh my dirs.

Schermata 2020-05-12 alle 18 16 55

Composer deprecation notice

Installing on production we receive this error:

Deprecation Notice: Class Alphametric\Validation\Rules\Misc\Iso3166Alpha3 located in ./vendor/alphametric/laravel-validation-rules/src/misc/Iso3166Alpha3.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201

Deprecation Notice: Class Alphametric\Validation\Rules\Misc\Iso3166Alpha2 located in ./vendor/alphametric/laravel-validation-rules/src/misc/Iso3166Alpha2.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:201

Inconsistent country coding

Citizen identification mixes capitalisation and length from country code validation rules in same repo (laravel-validation-rules).

Which means that :=
Using 'US' for country code passes but fails citizen identification rule.
Using 'USA' for country code passes both rules.
Using 'GB' for country code passes but fails citizen identification rule.
Using 'GBR' for country code passes but fails citizen identification rule.
Using 'UK' for country code fails but passes citizen identification rule.
Using 'FR' for country code passes both rules.
Using 'FRA' for country code passes but fails citizen identification rule.

Expected behaviour :=
A form submitted from a web site using a single field for (country code/name) will pass or fail consistently including error messages.

Note : because
'GB' => 'United Kingdom of Great Britain and Northern Ireland',
'GBR' => 'United Kingdom',
A bug can be created when refactoring the country list for use outside of dedicated rules, because
assertTrue($country->setCountry('GB')->name(),$country->setCountry('GBR')->name());
will fail.

CitizenIdentification uses
The identification type to use ('usa', 'uk', 'fr').
where as
CountryCode uses
Array of countries with their ISO 3166-1 alpha-2 codes.

  • 'FR' => 'France',
  • 'GB' => 'United Kingdom of Great Britain and Northern Ireland',
  • 'US' => 'United States of America',

Array of countries with their ISO 3166-1 alpha-3 codes.

  • 'FRA' => 'France',
  • 'GBR' => 'United Kingdom',
  • 'USA' => 'United States of America',

Default validation messages defined in rule classes not working

I have done fresh install of package, and when testing country code validation, the default validation message defined in the class is not returned, rather returns validation.country_code message.

Screenshot 2019-10-20 at 16 57 10

This can be fixed on user side by defining a language file entry for given rule.

However, to make use of the default message defined in the package, it need to fix a check in the helper class

public static function getLocalizedErrorMessage($key, $default)
{
    return trans("validation.$key") === $key ? $default : trans("validation.$key");
}

should be

public static function getLocalizedErrorMessage($key, $default)
{
    return trans("validation.$key") === "validation.$key" ? $default : trans("validation.$key");
}

In initial comparison the result of translation has a validation. prefix which is not there in the key, thus will always return false and not return default message

New namespace "Axiom" doesn't work on 2.1

Hi there and first thx for your work !

I directly installed 2.1 without older version before.
"use Axiom... " doesn't work
Namespace hasn't updated and I have to use the old one "Alphametric..."

Domain validation rule is faulty (I think)

Adding the following test cases to DomainTest fails:

$this->assertFalse(validator(['domain' => 'google'], $rule)->passes()); // fails
$this->assertFalse(validator(['domain' => 1], $rule)->passes()); // fails

Telephone number validation for more countries

Hello! I think telephone number rule could be extended to support more countries by wrapping this lib: https://github.com/giggsey/libphonenumber-for-php.

Mu suggestion is to make it work like the citizen identification validation, where the country code is passed in and the validation occurs based on the country.

We could also validate not only if phone numbers are correct but also types. (Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP and Personal Numbers)

Do you think it's a good addition to this package?

Rule syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST)

Hi there !

I got the ParseError above when I did
protected function validator(array $data) { return Validator::make($data, [ 'login' => ['required', 'string', 'max:255', new WithoutWhitespace] ]); }
Capture d’écran 2020-06-04 à 15 56 44

My setup :

  • Laravel 7
  • php 7.4.6
  • axiom 3.1

Edit : I tried using another validator rule (the TelephoneNumber one) from your package but got the same error.
Did I make something wrong ?

Thx for your answer !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.