Hi
Suppose this is my DTO
public class AnyDto
{
[Required(ErrorMessage="Name is required")]
public string Name { get; set;}
}
Or suppose this is my Validator Class
public class AnyDtoValidator : AbstractValidator<AnyDto>
{
public AnyDtoValidator()
{
RuleFor(x => x.Name).NotNull().WithMessage("Name is required");
}
}
I want to localize my errror message which is Name is required
.
How do I do it ?
Kindly provide solution in both cases DTO/Fluent Validators
6 Answer(s)
-
0
How do we
Check Duplicate Entities
in Fluent Validators ? Where this duplicate check should be done? Contract/Domain/Application project ? Cause I have my Validator's in Application.Contracts project. Is this the right way to do it? -
0
-
0
Thanks @liangshiwei
My DTO's are as below :
CustomerDto
public class CustomerDto : AuditedEntityDto<Guid> { .... }
AddressDto
public class AddressDto : AuditedEntityDto<Guid> { .... }
OrderDto
public class OrderDto : AuditedEntityDto<Guid> { public CustomerDto Customer { get; set; } public AddressDto Address { get; set; } }
As per your above solution I tried injecting
IStringLocalizer<MyProjectResource> localizer
as belowCustomerDtoValidator
public class CustomerDtoValidator : AbstractValidator<CustomerDto> { public CustomerDtoValidator(IStringLocalizer<MyProjectResource> _localizer) { .... } }
AddressDtoValidator
public class AddressDtoValidator : AbstractValidator<AddressDto> { public AddressDtoValidator(IStringLocalizer<MyProjectResource> _localizer) { .... } }
But I am not able to Implement below code for OrderDto :
public class OrderDtoValidator:AbstractValidator<SupplierCombinedDto> { public OrderDtoValidator() { RuleFor(x => x.Customer).SetValidator(new CustomerDtoValidator()); <-- ERROR RuleFor(x => x.Address).SetValidator(new AddressDtoValidator()); <-- ERROR } }
ERROR: There is no argument given that corresponds to the required formal parameter '_localizer' of CustomerDtoValidator(IStringLocalizer
What should I pass as argument ?
-
0
Try :
public class OrderDtoValidator:AbstractValidator<SupplierCombinedDto> { public OrderDtoValidator(IStringLocalizer<MyProjectResource> _localizer) { RuleFor(x => x.Customer).SetValidator(new CustomerDtoValidator(_localizer)); RuleFor(x => x.Address).SetValidator(new AddressDtoValidator(_localizer)); } }
-
0
Thanks @liangshiwei
It worked, Just last question which remained unanswered before How do we
Check Duplicate Entities
in Fluent Validators ? I want to cross check from my Address table whether this record is already present in my table ( i.e duplicate address ) Is it possible in Fluent Validator ? And how do I do it ? -
0
I do n’t know much about FluentValidation, you can maybe inject repository to validator class and check duplicate entities. But I suggest you
Check Duplicate Entities
in thedomain
layer.