Raxol.Security.InputValidator (Raxol v2.0.1)

View Source

Secure input validation and sanitization module.

Provides comprehensive input validation with security in mind, preventing common attacks like SQL injection, XSS, and command injection.

Summary

Functions

Creates a validator function for reuse.

Common validation patterns.

Sanitizes common input types.

Validates a single field against its rules.

Validates a map of inputs against a schema.

Validates multiple fields in parallel for performance.

Types

field_spec()

@type field_spec() :: %{
  :name => atom(),
  :rules => [validation_rule()],
  optional(:sanitize) => boolean(),
  optional(:error_message) => String.t()
}

validation_rule()

@type validation_rule() ::
  {:type, atom()}
  | {:required, boolean()}
  | {:min_length, non_neg_integer()}
  | {:max_length, non_neg_integer()}
  | {:format, Regex.t()}
  | {:in, list()}
  | {:custom, function()}

Functions

create_validator(rules, opts \\ [])

Creates a validator function for reuse.

Examples

username_validator = create_validator([
  {:type, :string},
  {:min_length, 3},
  {:max_length, 20},
  {:format, ~r/^[a-zA-Z0-9_]+$/}
])

username_validator.("john_doe")
# => {:ok, "john_doe"}

patterns()

Common validation patterns.

sanitize(value, type)

Sanitizes common input types.

validate_field(value, field_spec)

Validates a single field against its rules.

validate_inputs(inputs, schema)

Validates a map of inputs against a schema.

Examples

schema = [
  %{name: :username, rules: [{:type, :string}, {:min_length, 3}, {:max_length, 20}]},
  %{name: :email, rules: [{:type, :string}, {:format, ~r/^[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}$/}]},
  %{name: :age, rules: [{:type, :integer}, {:min, 18}, {:max, 120}]}
]

validate_inputs(%{username: "john", email: "john@example.com", age: 25}, schema)

validate_parallel(inputs, schema)

Validates multiple fields in parallel for performance.