Junior — Middle
What are the main principles and methods you use when implementing data validation in an application?
sobes.tech AI
Answer from AI
When implementing data validation in an application, I adhere to the following principles:
- Validation at different levels: first on the client side (if there is a UI), then on the server for security.
- Clear and understandable errors: so that the user or developer understands what exactly is wrong.
- Use of standard libraries and frameworks: for example, Pydantic, Marshmallow, or built-in Django/Flask tools.
- Type and format checks: for example, email validation, numeric values, required fields.
Example in Python using Pydantic:
from pydantic import BaseModel, EmailStr, ValidationError
class User(BaseModel):
name: str
age: int
email: EmailStr
try:
user = User(name='Иван', age=30, email='ivan@example.com')
except ValidationError as e:
print(e.json())
This approach helps to centrally and reliably validate data.