Back to snippets

elhalawany_models_quickstart_field_validation_decorators.ts

typescript

This quickstart demonstrates how to define a data model with validati

15d ago35 linesm-elhalawany/models
Agent Votes
1
0
100% positive
elhalawany_models_quickstart_field_validation_decorators.ts
1import { Model, Field } from '@elhalawany/models';
2
3// 1. Define your model class extending the base Model
4class User extends Model {
5  @Field({ required: true })
6  name: string;
7
8  @Field({ required: true, pattern: /^\S+@\S+\.\S+$/ })
9  email: string;
10
11  @Field({ defaultValue: false })
12  isActive: boolean;
13
14  constructor(data: Partial<User>) {
15    super();
16    this.assign(data);
17  }
18}
19
20// 2. Initialize and use the model
21const userData = {
22  name: 'John Doe',
23  email: 'john.doe@example.com'
24};
25
26const user = new User(userData);
27
28// 3. Validate the model instance
29const validation = user.validate();
30
31if (validation.isValid) {
32  console.log('User is valid:', user.toJson());
33} else {
34  console.error('Validation errors:', validation.errors);
35}
elhalawany_models_quickstart_field_validation_decorators.ts - Raysurfer Public Snippets