Skip to content

Commit

Permalink
added validation section to docs
Browse files Browse the repository at this point in the history
  • Loading branch information
ddjerqq committed Mar 5, 2024
1 parent fc0a52f commit 0b840d3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 16 deletions.
Empty file added docs/api.md
Empty file.
68 changes: 52 additions & 16 deletions docs/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,57 @@

QuickForm has two types of validation

- Microsoft's `DataAnnotationsValidator`
- `DataAnnotationsValidator`
- `Blazored.FluentValidationValidator`

## Before you start

Make sure that:

- QuickForm package is added to your project.
- QuickForm is properly imported.
- You have your fluent validation properly set up.

## DataAnnotation Validation

There are many data annotation attributes supported for validation,
most built-into C#, but some specific to QuickForm

Please refer to the [Customizing with attributes](attribute-customization.md) section for more
information about supported attributes
## DataAnnotationAttributes

```csharp
public class User
{
[Required]
public string Name { get; set; }

[Range(18, 100. ErrorMessage = "You must be 18 years or older to register")]
public int Age { get; set; }

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z]).{8,32}$", ErrorMessage = "Password must have at least 8 characters, one uppercase letter, one lowercase letter...")]
public string Password { get; set; }
}
```

## FluentValidation

```csharp
public class ProductCreate
{
public string Name { get; set; }

public decimal Price { get; set; }
}

public class ProductCreateValidator : AbstractValidator<ProductCreate>
{
public ProductCreateValidator(IProductRepository productRepository)
{
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Name is required")
.MustAsync(async (name, product, cancellationToken) => {
var product = await productRepository.GetByName(name);
return product == null;
})
.WithMessage("Product with this name already exists");

RuleFor(x => x.Price)
.GreaterThan(0)
.WithMessage("Price must be greater than 0");
}
}
```


!!! info

These validation rules will be automatically applied to your form,
and all fields will get validated when they are changed, even asynchronously.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ nav:
- Customization: customization.md
- Validation: validation.md
- Attributes: attributes.md
- API: api.md

theme:
name: material
Expand Down

0 comments on commit 0b840d3

Please sign in to comment.