Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Colour Laravel Package

laravel-validation-rules/colour

Laravel validation rules for colour values. Validate CSS colour formats such as hex, RGB, RGBA, HSL and HSLA, plus named colours, using simple rule objects you can drop straight into form requests and validators.

View on GitHub
Deep Wiki
Context7

Getting Started

The package ships a single invokable rule object, so there is no service provider or config file to publish. Install it with Composer and you are ready:

composer require laravel-validation-rules/colour

The first place to look is the README’s usage snippet and the src/ directory — in practice you will only ever interact with LaravelValidationRules\Colour\Colour. The typical first use case is a form that accepts a colour from a colour picker or a theme settings page:

use LaravelValidationRules\Colour\Colour;

$request->validate([
    'brand_colour' => ['required', 'string', new Colour],
]);

The rule validates the common CSS colour notations (hex, rgb(), rgba(), hsl(), hsla()), which covers what 99% of colour pickers submit. If you need to restrict the input to a specific notation, pass the relevant format constant to the constructor:

new Colour(Colour::HEX)
new Colour([Colour::HEX, Colour::RGB])

Start with the plain new Colour rule in a form request; only reach for format constants once you have a concrete reason to reject valid-but-unexpected notation from a client.

Implementation Patterns

Form requests. Because the rule is a plain ValidationRule, it composes naturally with the rest of your rules. A dedicated request keeps the validation concern out of controllers and lets you return a structured 422 response for API clients:

class UpdateThemeRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'primary'   => ['required', 'string', new Colour],
            'secondary' => ['nullable', 'string', new Colour],
            'accent'    => ['nullable', 'string', new Colour(Colour::HEX)],
        ];
    }
}

Combining with format constraints. When you know the source (for example, an HTML <input type="color">, which always submits #rrggbb), tighten the rule to Colour::HEX. This converts “the user typed something weird” into a clear validation failure instead of storing an HSL string that your CSS layer cannot render.

Inline rules in Livewire / Filament. The rule is invokable, so it works anywhere Laravel’s validator runs — $this->validate() in Livewire components, Rule::make()-style builders, or Filament form field ->rules([new Colour]). Keep the string rule in front of it so PHP does not try to run a regex against an array or null.

Pairing with a normaliser. Treat validation as a gate, not a transformer. Once the rule passes, store the value in a canonicalised form (e.g. cast to lowercase, or convert to hex) in a small action or model mutator so downstream CSS does not have to handle five notations. Validating first and normalising second keeps the rule package focused on correctness.

API and JSON contracts. When the same endpoint serves web and mobile, put the rule on the request and also mirror it in the OpenAPI schema (e.g. pattern: '^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$' for the hex-only case). The package does not generate schema hints, so keeping the two in sync is your responsibility.

Gotchas and Tips

  • Named colours are not validated. red, rebeccapurple, and transparent are not part of the default accepted formats. If your UI exposes a CSS colour-name picker, you either need to map names to hex before validation or add a separate Rule::in([...]) alongside the colour rule.
  • Hex variants are all accepted. #fff, #ffff, #ffffff, and #ffffffff are all valid. If your storage or CSS pipeline only handles 6-digit hex, constrain the rule yourself with a regex after new Colour(Colour::HEX), or normalise before saving.
  • Alpha channel is allowed by default. rgba() and hsla() pass even if your database column is char(7). Decide explicitly whether transparency is a feature or a bug for each field.
  • Empty strings pass unless required is present. The default Laravel “empty means skip” behaviour applies to rule objects too, so 'nullable' plus new Colour will accept null and ''. If an empty string should be a hard error, add required.
  • # is mandatory for hex in most builds. Bare ffffff will usually fail. If you accept hex from a legacy source, strip or prepend the # in a prepareForValidation() method on the form request instead of loosening the rule.
  • Whitespace inside functions is format-sensitive. rgb(0,0,0) and rgb(0, 0, 0) are both commonly accepted, but rgb (0,0,0) or RGB(0,0,0) may not be — check the regex in src/ before relying on it for user-pasted input, and trim() the value in a prepareForValidation() if you are unsure.
  • No config file, no extension points. There is no published config to override the regexes or add formats. If you need a custom notation (CSS Color 4 lab(), lch(), color(display-p3 …)), write your own ValidationRule — do not expect the package to grow one.
  • Error messages. Override messages() on the form request to give a useful hint ('Please enter a hex colour such as #1a2b3c.') rather than the package’s generic “The :attribute is not a valid colour.” The default message is easy to miss in a form with many fields.
  • Last release was February 2023. The rule is small and stable, so this is not a practical risk, but pin the version in composer.json and add a quick test in your own suite so an upgrade of Laravel (or the package) cannot silently change what counts as a valid colour.
  • Test with real picker output. Add a Pest/PHPUnit test that feeds in the exact strings your colour picker emits (including the trailing newline some pickers append) — that catches the majority of “works locally, fails in production” bugs with this kind of rule.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment