or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdcore-functions.mdexceptions.mdindex.mdschema-management.mdvalidators.md

validators.mddocs/

0

# Built-in Validators

1

2

Comprehensive set of validators for all common data types with constraint support for building robust validation schemas. Yamale provides validators for primitive types, collections, patterns, and specialized formats.

3

4

## Base Validator

5

6

All validators inherit from the base Validator class and support common parameters.

7

8

```python { .api }

9

class Validator:

10

"""

11

Base class for all validators.

12

"""

13

14

def __init__(self, *args, **kwargs):

15

"""

16

Initialize validator with arguments and constraints.

17

18

Common Parameters:

19

- required (bool): Whether field is required (default: True)

20

- none (bool): Whether None values are allowed for optional fields (default: True)

21

22

Attributes:

23

- args: Positional arguments passed to validator

24

- kwargs: Keyword arguments passed to validator

25

- is_required: Whether field is required

26

- constraints: List of constraint classes for this validator

27

- value_type: Expected value type for this validator

28

"""

29

30

def validate(self, value):

31

"""

32

Validate a value against this validator.

33

34

Parameters:

35

- value: Value to validate

36

37

Returns:

38

list: List of error messages (empty if valid)

39

"""

40

41

def is_valid(self, value):

42

"""

43

Check if value is valid (returns boolean).

44

45

Parameters:

46

- value: Value to validate

47

48

Returns:

49

bool: True if valid, False otherwise

50

"""

51

52

def fail(self, value):

53

"""

54

Generate error message for invalid value.

55

56

Parameters:

57

- value: The invalid value

58

59

Returns:

60

str: Error message

61

"""

62

63

def get_name(self):

64

"""

65

Get display name for this validator.

66

67

Returns:

68

str: Validator name for error messages

69

"""

70

71

@property

72

def tag(self):

73

"""Validator tag used in schema syntax."""

74

75

@property

76

def is_optional(self):

77

"""Whether this validator allows optional fields."""

78

79

@property

80

def can_be_none(self):

81

"""Whether None values are accepted for optional fields."""

82

83

# Common constraint attributes

84

constraints: list # List of constraint classes

85

value_type: type # Expected Python type

86

args: tuple # Validator arguments

87

kwargs: dict # Validator keyword arguments

88

is_required: bool # Whether field is required

89

```

90

91

## Capabilities

92

93

### String Validation

94

95

Validates string values with extensive constraint options for length, content, and pattern matching.

96

97

```python { .api }

98

class String(Validator):

99

"""

100

String validator with comprehensive constraint support.

101

Schema syntax: str(min=int, max=int, equals=str, starts_with=str, ends_with=str, matches=regex, exclude=str, ignore_case=bool, multiline=bool, dotall=bool)

102

"""

103

```

104

105

Constraint parameters:

106

- `min`: Minimum string length

107

- `max`: Maximum string length

108

- `equals`: Exact string match (case-sensitive by default)

109

- `starts_with`: String must start with specified value

110

- `ends_with`: String must end with specified value

111

- `matches`: Regular expression pattern matching

112

- `exclude`: Reject strings containing any character from excluded set

113

- `ignore_case`: Case-insensitive matching for equals/starts_with/ends_with/matches

114

- `multiline`: Enable multiline regex mode (only with `matches`)

115

- `dotall`: Enable dotall regex mode (only with `matches`)

116

117

Schema examples:

118

```yaml

119

# Basic string validation

120

name: str()

121

122

# Length constraints

123

username: str(min=3, max=20)

124

125

# Content validation

126

status: str(equals="active")

127

filename: str(ends_with=".yaml")

128

url: str(starts_with="https://")

129

130

# Pattern validation

131

email: str(matches="^[^@]+@[^@]+\.[^@]+$")

132

clean_input: str(exclude="<>\"'")

133

134

# Case-insensitive matching

135

status: str(equals="Active", ignore_case=True)

136

```

137

138

### Numeric Validation

139

140

Validators for integer and floating-point numbers with range constraints.

141

142

```python { .api }

143

class Integer(Validator):

144

"""

145

Integer validator with range constraints.

146

Schema syntax: int(min=int, max=int)

147

"""

148

149

class Number(Validator):

150

"""

151

Number validator for integers and floats with range constraints.

152

Schema syntax: num(min=float, max=float)

153

"""

154

```

155

156

Schema examples:

157

```yaml

158

# Basic numeric validation

159

age: int()

160

score: num()

161

162

# Range constraints

163

port: int(min=1, max=65535)

164

percentage: num(min=0.0, max=100.0)

165

temperature: num(min=-273.15) # Absolute zero minimum

166

```

167

168

### Boolean and Null Validation

169

170

Simple validators for boolean and null values.

171

172

```python { .api }

173

class Boolean(Validator):

174

"""

175

Boolean validator.

176

Schema syntax: bool()

177

"""

178

179

class Null(Validator):

180

"""

181

Null/None validator.

182

Schema syntax: null()

183

"""

184

```

185

186

Schema examples:

187

```yaml

188

# Boolean validation

189

enabled: bool()

190

debug_mode: bool()

191

192

# Null validation

193

optional_field: null()

194

```

195

196

### Collection Validation

197

198

Validators for lists and maps with content and size constraints.

199

200

```python { .api }

201

class List(Validator):

202

"""

203

List validator with element type and size constraints.

204

Schema syntax: list([validators], min=int, max=int)

205

"""

206

207

class Map(Validator):

208

"""

209

Map/dictionary validator with key/value type and size constraints.

210

Schema syntax: map([value_validators], key=key_validator, min=int, max=int)

211

"""

212

```

213

214

Schema examples:

215

```yaml

216

# Basic collections

217

tags: list()

218

metadata: map()

219

220

# Typed collections

221

scores: list(int())

222

user_data: map(str()) # Values must be strings

223

224

# Size constraints

225

required_items: list(str(), min=1, max=5)

226

small_config: map(any(), max=10)

227

228

# Key type validation

229

numeric_lookup: map(str(), key=int()) # Integer keys, string values

230

231

# Complex nested validation

232

users: list(include('user'))

233

permissions: map(list(str()), key=str()) # String keys, list of strings values

234

```

235

236

### Choice and Union Validation

237

238

Validators for enumerated values and union types.

239

240

```python { .api }

241

class Enum(Validator):

242

"""

243

Enum validator for fixed set of allowed values.

244

Schema syntax: enum(value1, value2, ...)

245

"""

246

247

class Any(Validator):

248

"""

249

Any validator - accepts one of several validator types.

250

Schema syntax: any([validators])

251

"""

252

253

class Subset(Validator):

254

"""

255

Subset validator - accepts one or more of several validator types as a list.

256

Schema syntax: subset([validators], allow_empty=bool)

257

"""

258

```

259

260

Schema examples:

261

```yaml

262

# Enumerated values

263

status: enum('draft', 'published', 'archived')

264

priority: enum(1, 2, 3, 'high', 'medium', 'low')

265

266

# Union types

267

id: any(int(), str()) # Either integer or string

268

config_value: any(str(), num(), bool())

269

270

# Subset validation (automatically validates as list)

271

permissions: subset(str()) # List of strings

272

mixed_data: subset(int(), str(), bool()) # List containing any combination

273

274

# Allow empty subsets

275

optional_tags: subset(str(), allow_empty=True)

276

```

277

278

### Pattern Validation

279

280

Advanced pattern matching with regular expressions.

281

282

```python { .api }

283

class Regex(Validator):

284

"""

285

Regular expression validator with multiple pattern support.

286

Schema syntax: regex(pattern1, pattern2, ..., name=str, ignore_case=bool, multiline=bool, dotall=bool)

287

"""

288

```

289

290

Schema examples:

291

```yaml

292

# Basic pattern matching

293

ssn: regex('^\\d{3}-\\d{2}-\\d{4}$')

294

295

# Multiple acceptable patterns

296

phone: regex('^\\d{10}$', '^\\d{3}-\\d{3}-\\d{4}$', '^\\(\\d{3}\\)\\s\\d{3}-\\d{4}$')

297

298

# Named patterns for better error messages

299

user_id: regex('^[a-zA-Z0-9_]+$', name='alphanumeric identifier')

300

301

# Case-insensitive matching

302

code: regex('^[A-Z]{2,4}$', ignore_case=True)

303

304

# Multiline patterns

305

text_block: regex('.*^Summary:', multiline=True, dotall=True)

306

```

307

308

### Date and Time Validation

309

310

Validators for date and timestamp formats with range constraints.

311

312

```python { .api }

313

class Day(Validator):

314

"""

315

Date validator for YYYY-MM-DD format.

316

Schema syntax: day(min=date_str, max=date_str)

317

"""

318

319

class Timestamp(Validator):

320

"""

321

Timestamp validator for YYYY-MM-DD HH:MM:SS format.

322

Schema syntax: timestamp(min=timestamp_str, max=timestamp_str)

323

"""

324

```

325

326

Schema examples:

327

```yaml

328

# Date validation

329

birth_date: day()

330

start_date: day(min='2020-01-01')

331

end_date: day(max='2030-12-31')

332

project_date: day(min='2023-01-01', max='2023-12-31')

333

334

# Timestamp validation

335

created_at: timestamp()

336

login_time: timestamp(min='2023-01-01 00:00:00')

337

scheduled_time: timestamp(min='2023-06-01 09:00:00', max='2023-06-01 17:00:00')

338

```

339

340

### Network and Format Validation

341

342

Specialized validators for network addresses and version strings.

343

344

```python { .api }

345

class Ip(Validator):

346

"""

347

IP address validator for IPv4 and IPv6.

348

Schema syntax: ip(version=int)

349

"""

350

351

class Mac(Validator):

352

"""

353

MAC address validator.

354

Schema syntax: mac()

355

"""

356

357

class SemVer(Validator):

358

"""

359

Semantic versioning validator.

360

Schema syntax: semver()

361

"""

362

```

363

364

Schema examples:

365

```yaml

366

# Network addresses

367

server_ip: ip()

368

ipv4_only: ip(version=4)

369

ipv6_only: ip(version=6)

370

device_mac: mac()

371

372

# Version strings

373

package_version: semver() # e.g., "1.2.3", "2.0.0-alpha.1"

374

```

375

376

### Include Validation

377

378

Validator for referencing defined schema includes.

379

380

```python { .api }

381

class Include(Validator):

382

"""

383

Include validator for referencing schema includes.

384

Schema syntax: include('include_name', strict=bool)

385

"""

386

```

387

388

Schema examples:

389

```yaml

390

# Basic include usage

391

user: include('person')

392

admin: include('person')

393

394

# Include with strict mode control

395

flexible_user: include('person', strict=False) # Allow extra fields

396

strict_config: include('settings') # Default strict mode

397

398

---

399

# Include definitions

400

person:

401

name: str()

402

age: int(min=0)

403

404

settings:

405

debug: bool()

406

timeout: int()

407

```

408

409

## Custom Validators

410

411

Yamale supports creating custom validators by extending the base Validator class.

412

413

```python { .api }

414

class CustomValidator(Validator):

415

"""

416

Base class for creating custom validators.

417

"""

418

419

tag = "custom_name" # Schema syntax identifier

420

421

def _is_valid(self, value):

422

"""

423

Implement validation logic.

424

425

Parameters:

426

- value: Value to validate

427

428

Returns:

429

bool: True if valid, False otherwise

430

"""

431

```

432

433

Example custom validator:

434

435

```python

436

import yamale

437

from yamale.validators import Validator, DefaultValidators

438

439

class EmailValidator(Validator):

440

tag = 'email'

441

442

def _is_valid(self, value):

443

if not isinstance(value, str):

444

return False

445

return '@' in value and '.' in value and len(value) > 5

446

447

# Register custom validator

448

custom_validators = DefaultValidators.copy()

449

custom_validators['email'] = EmailValidator

450

451

# Use in schema

452

schema = yamale.make_schema(

453

content="contact: email()",

454

validators=custom_validators

455

)

456

```

457

458

## Default Validators Dictionary

459

460

```python { .api }

461

DefaultValidators = {

462

# Access dictionary mapping validator tags to classes

463

'str': String,

464

'int': Integer,

465

'num': Number,

466

'bool': Boolean,

467

'null': Null,

468

'list': List,

469

'map': Map,

470

'enum': Enum,

471

'any': Any,

472

'subset': Subset,

473

'include': Include,

474

'regex': Regex,

475

'day': Day,

476

'timestamp': Timestamp,

477

'ip': Ip,

478

'mac': Mac,

479

'semver': SemVer,

480

# Also accessible by class name: 'String': String, etc.

481

}

482

```

483

484

This dictionary is used by default when creating schemas and can be extended with custom validators.