# The Pattern constraint failed

Source: https://xmlvalid.com/errors/pattern-constraint-failed

> A value does not match the regular expression its type requires.

The message, as .NET reports it: `The 'code' element is invalid - The value 'ab-12' is invalid according to its datatype 'Code' - The Pattern constraint failed.`

## Why it happens

- The wrong letter case, length or separator for a code.
- Leading or trailing spaces, which the pattern has to match too.

## How to fix it

- Look the type up in the schema and compare the value with its `xs:pattern`; the pattern has to match the whole value.
- .NET throws an `XmlSchemaValidationException` at the first schema error unless `XmlReaderSettings.ValidationEventHandler` is set, which then receives every one with its line and position. A well-formedness error is an `XmlException` and ends reading whatever the settings.

## The same problem in xmlvalid

libxml2, which xmlvalid validates with, reports it as [[facet 'pattern'] The value is not accepted by the pattern](https://xmlvalid.com/errors/facet-pattern): `Element 'code': [facet 'pattern'] The value 'ab-12' is not accepted by the pattern '[A-Z]{3}-[0-9]{4}'.`

## Example that fails

```xml
<order currency="EUR">
  <id>A-1</id>
  <qty>1</qty>
  <code>ab-12</code>
</order>
```

## Fixed

```xml
<order currency="EUR">
  <id>A-1</id>
  <qty>1</qty>
  <code>ABC-0012</code>
</order>
```
