> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pocketbase/pocketbase/llms.txt
> Use this file to discover all available pages before exploring further.

# Password field

> Store bcrypt-hashed passwords with validation

The password field stores bcrypt-hashed passwords and is primarily used for the system `password` field in auth collections. It automatically hashes plain text passwords and provides validation methods.

## Configuration options

<ParamField path="pattern" type="string">
  Optional regex pattern to match against the plain password value. Leave empty to skip pattern validation.
</ParamField>

<ParamField path="min" type="int" default="0">
  Minimum required password length (in characters). Set to 0 for no minimum.
</ParamField>

<ParamField path="max" type="int" default="71">
  Maximum allowed password length (in characters). Defaults to 71 (bcrypt limit) if zero or not set.
</ParamField>

<ParamField path="cost" type="int" default="bcrypt.DefaultCost">
  Bcrypt cost factor (4-31). Higher values increase security but take longer to hash. Defaults to bcrypt.DefaultCost (10) if zero.
</ParamField>

<ParamField path="required" type="bool" default="false">
  When true, requires the field value to be a non-empty string.
</ParamField>

## How it works

The password field has special behavior:

1. **Setting values**: When you set a plain text password using `record.Set()`, it's automatically hashed
2. **Getting values**: `record.Get()` returns the plain password only before the record is saved, then returns empty string
3. **Hash access**: Use `record.GetString("password:hash")` to access the bcrypt hash
4. **Direct hash**: Use `record.SetRaw()` to set a pre-hashed bcrypt string directly

<Warning>
  Bcrypt has a maximum password length of 72 bytes. The field enforces a 71 character limit by default to account for encoding.
</Warning>

## Special getter

The password field provides a special getter to access the hash:

```go theme={null}
// Get the bcrypt hash
hash := record.GetString("password:hash")
```

## Validation rules

The password field validates:

* **Length**: Plain password must be between `min` and `max` characters
* **Pattern**: If specified, plain password must match the regex pattern
* **Hash errors**: Bcrypt hashing errors are captured and returned during validation
* **Required**: If enabled, hash must be non-empty

## Go examples

<Tabs>
  <Tab title="Basic usage">
    ```go theme={null}
    import "github.com/pocketbase/pocketbase/core"

    field := &core.PasswordField{
        Name:     "password",
        Required: true,
        Min:      8,
    }

    collection.Fields.Add(field)

    // Set plain password (will be hashed automatically)
    record.Set("password", "mySecurePassword123")

    // Before save: returns "mySecurePassword123"
    plainPassword := record.GetString("password")

    // After save: returns empty string
    plainPassword = record.GetString("password") // ""

    // Get hash anytime
    hash := record.GetString("password:hash")
    ```
  </Tab>

  <Tab title="With pattern validation">
    ```go theme={null}
    field := &core.PasswordField{
        Name:     "password",
        Required: true,
        Min:      8,
        Max:      64,
        Pattern:  "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$", // At least one lowercase, uppercase, and digit
    }

    collection.Fields.Add(field)

    // This will validate successfully
    record.Set("password", "SecurePass123")

    // This will fail validation (no uppercase)
    record.Set("password", "weakpass123")
    ```
  </Tab>

  <Tab title="Custom bcrypt cost">
    ```go theme={null}
    import "golang.org/x/crypto/bcrypt"

    field := &core.PasswordField{
        Name:     "password",
        Required: true,
        Min:      10,
        Cost:     12, // Higher cost = more secure but slower
    }

    collection.Fields.Add(field)

    record.Set("password", "myPassword123")
    ```
  </Tab>

  <Tab title="Setting pre-hashed password">
    ```go theme={null}
    import "golang.org/x/crypto/bcrypt"

    field := &core.PasswordField{
        Name:     "password",
        Required: true,
    }

    collection.Fields.Add(field)

    // Generate hash manually
    hash, err := bcrypt.GenerateFromPassword(
        []byte("myPassword123"),
        bcrypt.DefaultCost,
    )
    if err != nil {
        // handle error
    }

    // Set hash directly (bypasses hashing)
    record.SetRaw("password", string(hash))

    // Getting password returns empty string
    pwd := record.GetString("password") // ""

    // Get hash
    hash = record.GetString("password:hash")
    ```
  </Tab>
</Tabs>

## Password validation

The password field value can be validated against a plain text password:

```go theme={null}
// Get the password field value
passwordValue := record.GetRaw("password").(*core.PasswordFieldValue)

// Validate against plain text
isValid := passwordValue.Validate("userEnteredPassword")

if isValid {
    // Password matches
} else {
    // Password doesn't match
}
```

## Database column type

```sql theme={null}
TEXT DEFAULT '' NOT NULL
```

## Common password patterns

<CodeGroup>
  ```go Minimum complexity theme={null}
  Pattern: "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$"
  // At least 8 chars, one lowercase, one uppercase, one digit
  ```

  ```go With special characters theme={null}
  Pattern: "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&]).{8,}$"
  // At least 8 chars, lowercase, uppercase, digit, and special char
  ```

  ```go No whitespace theme={null}
  Pattern: "^\\S+$"
  // No spaces or whitespace characters
  ```

  ```go Alphanumeric only theme={null}
  Pattern: "^[a-zA-Z0-9]+$"
  // Letters and numbers only
  ```
</CodeGroup>

## Bcrypt cost levels

<Info>
  Bcrypt cost determines how many iterations are used. Higher cost = exponentially more time:

  * Cost 4: \~2ms (testing only)
  * Cost 10: \~50ms (default, good balance)
  * Cost 12: \~200ms (high security)
  * Cost 14: \~800ms (very high security)
  * Cost 15+: Use with caution (can take several seconds)
</Info>

## Security best practices

<Note>
  * Never store or log plain text passwords
  * Use a minimum length of at least 8 characters (12+ recommended)
  * Consider requiring complexity through pattern validation
  * Use default bcrypt cost (10) unless you have specific security requirements
  * The plain password is automatically cleared after save
  * Bcrypt automatically includes a salt, no need to add one separately
  * Hashed passwords are approximately 60 characters long
</Note>

## Auth collection integration

This field is automatically used in auth collections:

```go theme={null}
// Auth collections have a built-in password field
// You typically don't need to add it manually

collection := &core.Collection{
    Name: "users",
    Type: core.CollectionTypeAuth,
}

// The password field is automatically configured
```

## Zero value

The zero value for password fields is an empty string `""`.
