@@ -8,8 +8,52 @@ Elixir library for validating credit card numbers (a port of [credit_card_valida
8
8
9
9
## Documentation
10
10
11
+ See the tests folder for examples of how to use this library.
12
+
11
13
API documentation can be found at [ http://hexdocs.pm/credit_card ] ( http://hexdocs.pm/credit_card )
12
14
15
+ ### Using with Phoenix and Ecto
16
+
17
+ ``` elixir
18
+ defmodule MyApp .Card do
19
+ use MyApp .Web , :model
20
+
21
+ schema " cards" do
22
+ field :card_number , :integer
23
+ field :name_on_card , :string
24
+ field :valid_from , Ecto .Date
25
+ field :expires , Ecto .Date
26
+ timestamps
27
+ end
28
+
29
+ @required_fields ~w( card_number name_on_card valid_from expires)
30
+ @optional_fields ~w( )
31
+
32
+ @doc """
33
+ Creates a changeset based on the `model` and `params`.
34
+
35
+ If no params are provided, an invalid changeset is returned
36
+ with no validation performed.
37
+ """
38
+ def changeset (model, params \\ :empty ) do
39
+ model
40
+ |> cast (params, @required_fields , @optional_fields )
41
+ |> validate_credit_card (:card_number )
42
+ end
43
+
44
+ def validate_credit_card (changeset, field \\ :card_number , opts \\ []) do
45
+ validate_change changeset, field, fn _field , number ->
46
+ message = opts[:message ] || " Invalid credit card number"
47
+ if CreditCard .valid? (to_string (number)) do
48
+ []
49
+ else
50
+ [field, message]
51
+ end
52
+ end
53
+ end
54
+ end
55
+ ```
56
+
13
57
## TODO
14
58
15
59
Incorporate some ideas from [ Card] ( https://github.com/jessepollak/card )
@@ -24,5 +68,5 @@ The package can be installed as:
24
68
1 . Add credit_card to your list of dependencies in ` mix.exs ` :
25
69
26
70
def deps do
27
- [{:credit_card, "~> 0 .0.1 "}]
71
+ [{:credit_card, "~> 1 .0.0 "}]
28
72
end
0 commit comments