I am having trouble implementing validation in Blazor. I currently am able to validate via attributes for things such as valid Guid inputs or required fields etc.
What I am after is a way to validate that some user entered data is not present in a database. From what I have read this cannot be done via an attribute as it is not possible to get the database context.
Could someone point me in the right direction as to how to validate data such as this.
Many thanks,
1 Answer 1
You could do it with FluentValidation. With it you can create simple to complex validation rules for your models and you can also validate with database data as well.
Follow the steps below of an example to check for email address if already registered in database. Hopefully, this example will point you in the right direction.
Install:
The Accelist.FluentValidation.Blazor nuget will provide integration of fluentvalidation with blazor.
dotnet add package FluentValidation
dotnet add package Accelist.FluentValidation.Blazor
Register Validator
This will allow you inject DB context in your validator.
builder.Services.AddScoped<IValidator<FormModel>, FormModelValidator>();
Implementation
Add FluentValidation element inside your form. And create validator for your model with a rule for Email property to check value with database if it exists.
<EditForm Model="Form">
<FluentValidator></FluentValidator>
<div class="form-group">
<label for="email">Email</label>
<InputText id="email" type="email" class="form-control" @bind-Value="Form.Email"></InputText>
<ValidationMessage For="() => Form.Email"></ValidationMessage>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">
<i class="fas fa-chevron-up"></i>
Submit
</button>
</div>
</EditForm>
@code {
FormModel Form = new FormModel();
public class FormModel
{
public string Email { set; get; }
}
public class FormModelValidator : AbstractValidator<FormModel>
{
readonly AppDbContext DB;
readonly IServiceProvider SP;
public FormModelValidator(AppDbContext db, IServiceProvider sp)
{
this.DB = db;
this.SP = sp;
RuleFor(Q => Q.Email).NotEmpty().EmailAddress().MaximumLength(255)
.Must(BeUniqueEmail).WithMessage("Email address is already registered.");
}
bool BeUniqueEmail(string email)
{
var exist = DB.Account.Where(Q => Q.Email == email).Any();
return (exist == false);
}
}
}
4 Comments
Explore related questions
See similar questions with these tags.