Skip to main content

validate_hex_color

Function validate_hex_color 

Source
pub fn validate_hex_color(s: &str) -> Result<(), ValidationError>
Expand description

Validate a web-color hex code: #rgb, #rrggbb, #rgba, or #rrggbbaa. The # prefix is required; hex digits are case-insensitive. Anything else (named colors, rgb() / hsl() functions, hex without #) is rejected.

Useful for color-picker form fields in admin / theme-config surfaces. Pair with validate_max_length to bound the input to 9 characters total.

Examples:

  • validate_hex_color("#fff") → Ok(())
  • validate_hex_color("#ffaabb") → Ok(())
  • validate_hex_color("#FFAA00CC") → Ok(()) (8 = with alpha)
  • validate_hex_color("fff") → Err (missing #)
  • validate_hex_color("#ffffg") → Err (g not hex)
  • validate_hex_color("#ffff") → Err (4 chars: only valid shorthand is 3 / 6 / 4 / 8)

§Errors

ValidationError { code: "invalid_hex_color", ... }.