---
id: 696655d24b614176d4c9b789
title: "Challenge 166: Hex Validator"
challengeType: 29
dashedName: challenge-166
---

# --description--

Given a string, determine whether it is a valid CSS hex color. A valid CSS hex color must:

- Start with a `#`, and
- be followed by either 3 or 6 hexadecimal characters.

Hexadecimal characters are numbers `0` through `9` and letters `a` through `f` (case-insensitive).

# --hints--

`is_valid_hex("#123")` should return `True`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#123"), True)`)
}})
```

`is_valid_hex("#123abc")` should return `True`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#123abc"), True)`)
}})
```

`is_valid_hex("#ABCDEF")` should return `True`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#ABCDEF"), True)`)
}})
```

`is_valid_hex("#0a1B2c")` should return `True`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#0a1B2c"), True)`)
}})
```

`is_valid_hex("#12G")` should return `False`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#12G"), False)`)
}})
```

`is_valid_hex("#1234567")` should return `False`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#1234567"), False)`)
}})
```

`is_valid_hex("#12 3")` should return `False`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("#12 3"), False)`)
}})
```

`is_valid_hex("fff")` should return `False`.

```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_hex("fff"), False)`)
}})
```

# --seed--

## --seed-contents--

```py
def is_valid_hex(s):

    return s
```

# --solutions--

```py
def is_valid_hex(s):
    if not s.startswith("#"):
        return False

    hex_part = s[1:]
    if len(hex_part) not in (3, 6):
        return False

    for char in hex_part:
        if not char.lower() in "0123456789abcdef":
            return False

    return True
```
