Home > Software engineering >  How can I add validations to print my own error message
How can I add validations to print my own error message

Time:11-18

I am creating a customer model for my API and I've set my 'Name' and 'Email' fields as required. But when we leave those fields empty while creating a new customer, we got a built-in error from EF core , instead I want to show my own error message...how can I do that.

I've tried to add validations by code in my post method but It doesn't work...can anyone help me with that?...Thanks in advance

CodePudding user response:

If you want to do simple validation: Fluent Validation

public class UserRegisterValidator : AbstractValidator<User>
{
    public UserRegisterValidator()
    {
        RuleFor(r => r.email).NotEmpty().WithMessage("Email address cannot be empty.");
       .
       .
       .
    }
}

When adding a new user

UserRegisterValidator v = new UserRegisterValidator();
ValidationResult result = v.Validate(usr);

if (!result.IsValid) return StatusCode(StatusCodes.Status400BadRequest, result.Errors); //Returns the specified error message
if (result.IsValid)
{
   //If there is no error, the necessary actions are here
}
                

CodePudding user response:

If you want to use server side validation you can specify the error message in validation tags. For example:

 public class Movie
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name{ get; set; }
}

Then you can also add some DetailsProvider to get better details when calling the api:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    options.ModelMetadataDetailsProviders.Add(new NewtonsoftJsonValidationMetadataProvider());
}).AddNewtonsoftJson();

Validation in front end has some other scenarios. Take a look at https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0

  • Related