fix: add hex color validation to Category model and form (to solve #1247) (#1341)

- Added server-side validation to Category model to enforce 6-digit hex format for colors.
- Added HTML pattern attribute to category form for client-side validation.
- Updated tests to cover validation and fixed existing tests using shorthand hex colors.
This commit is contained in:
Louis
2026-04-01 20:27:29 +02:00
committed by GitHub
parent a90f9b7317
commit 8ed69132cf
4 changed files with 19 additions and 3 deletions

View File

@@ -264,7 +264,7 @@ class BudgetTest < ActiveSupport::TestCase
source_budget.update!(budgeted_spending: 4000, expected_income: 6000)
# Create a category only in the source budget
temp_category = Category.create!(name: "Temp #{Time.now.to_f}", family: family, color: "#aaa")
temp_category = Category.create!(name: "Temp #{Time.now.to_f}", family: family, color: "#aaaaaa")
source_budget.budget_categories.create!(category: temp_category, budgeted_spending: 100, currency: "USD")
target_budget = Budget.find_or_bootstrap(family, start_date: 1.month.ago)
@@ -283,7 +283,7 @@ class BudgetTest < ActiveSupport::TestCase
target_budget = Budget.find_or_bootstrap(family, start_date: 1.month.ago)
# Add a new category only to the target
new_category = Category.create!(name: "New #{Time.now.to_f}", family: family, color: "#bbb")
new_category = Category.create!(name: "New #{Time.now.to_f}", family: family, color: "#bbbbbb")
target_budget.budget_categories.create!(category: new_category, budgeted_spending: 0, currency: "USD")
target_budget.copy_from!(source_budget)

View File

@@ -40,4 +40,19 @@ class CategoryTest < ActiveSupport::TestCase
assert names.all? { |name| name.is_a?(String) }
assert_equal names, names.uniq # No duplicates
end
test "should accept valid 6-digit hex colors" do
[ "#FFFFFF", "#000000", "#123456", "#ABCDEF", "#abcdef" ].each do |color|
category = Category.new(name: "Category #{color}", color: color, lucide_icon: "shapes", family: @family)
assert category.valid?, "#{color} should be valid"
end
end
test "should reject invalid colors" do
[ "invalid", "#123", "#1234567", "#GGGGGG", "red", "ffffff", "#ffff", "" ].each do |color|
category = Category.new(name: "Category #{color}", color: color, lucide_icon: "shapes", family: @family)
assert_not category.valid?, "#{color} should be invalid"
assert_includes category.errors[:color], "is invalid"
end
end
end