Search code examples
c#asp.net.netasp.net-mvc.net-6.0

.NET C# - How to sanitize the required error messages from ViewModel?


I have a question as regards to the handling of error messages in a form which I created. Whenever the user doesn't fill out the information will be stored in here ModelState.Root.Children.

To iterate through every item/errorMessage, I firstly do a check if there is a sum of errors and then I proceed to access every string that corresponds to a field.

This is my public class for the viewmodel of my page. What I have achieved so far is to pass every error message to a List so that afterwards I can be able to print it out on a popup window on my front-end side.

public class LandingViewModel
{
    [Required]
    [Display(Name = "Introduce un nombre.")]
    public string ContactFormName { get; set; }

    [Required]
    [Display(Name = "Introduce un correo.")]
    public string ContactFormEmail { get; set; }

    [Required]
    [Display(Name = "Introduce un teléfono de contacto.")]
    public string ContactFormTel { get; set; }

    [Required]
    [Display(Name = "Introduce un teléfono de contacto.")]
    public string Reason { get; set; }

    [Required]
    [Display(Name = "Confirma la política de privacidad para enviar la solicitud.")]
    public bool ContactoPolitica { get; set; }

    public string ContactFormText { get; set; }
}

This my public class for creating the base response which will contain a status and a message to send over to the front-end side, it will possibly contain every error message if there is one.

public class BaseResponse
{
 public string status { get; set; }
 public string message { get; set; }
}

Lastly, here is my HttpPost which is fired through an AJAX request I have on my page.

[HttpPost]
[AllowAnonymous]
public async Task<BaseResponse> Landing(LandingViewModel model)
{
    string result = await registerService.SendEmailForContactLanding(model);
    var response = new BaseResponse();
    try
    {
        if (!string.IsNullOrEmpty(result) && ModelState.ErrorCount == 0)
        {
            ModelState.AddModelError(string.Empty, result);
            response.status = "KO";
            response.message = "No se ha podido enviar tu solicitud. Por favor, intentelo más tarde.";
        }

        string[] errors;

        if (ModelState.ErrorCount > 0)
        {
            List<string> errorMessages = new List<string>();
            foreach (var item in ModelState.Root.Children)
            {

                var errorMessage = item.Errors[0].ErrorMessage;
                errorMessages.Add(errorMessage);

            }
            // in here I will transform the List<string> to a response.message for my front-end
        }


        if (ModelState.IsValid)
        {
            response.status = "OK";
            response.message = "Tu petición se ha enviado correctamente.";
        }
    }
    catch (Exception ex)
    {
        response = new BaseResponse();
        response.status = "KO";
        response.message = "Ha habido un error con tu petición " + ex.Message;
    }

    return response;
}

What I want to get rid of is this: whenever the user doesn't fill out some of the fields, while I pass through the breakpoints, the error messages don't appear as are being written on my public class LandingViewModel.

For example, [Display(Name = "Introduce un nombre.")] would have to appear as "Introduce un nombre." but it does not. It appears like: "The Introduce un teléfono de contacto. field is required."

The field is required for some reason is being thrown inside every error message string. How is it possible to sanitize this kind of messages ?


Solution

  • By changing my ViewModel to this, it worked. I'm getting the error messages exactly as I wanted.

    public class LandingViewModel
    {
    
        [Required(ErrorMessage = "Introduce un nombre.")]
        public string ContactFormName { get; set; }
    
        [Required(ErrorMessage = "Introduce un correo.")]
        public string ContactFormEmail { get; set; }
    
    
        [Required(ErrorMessage = "Introduce un teléfono de contacto.")]
        public string ContactFormTel { get; set; }
    
    
        [Required(ErrorMessage = "Selecciona la razón de contacto.")]
        public string Reason { get; set; }
    
        [Required(ErrorMessage = "Confirma la política de privacidad para enviar la solicitud.")]
        public bool ContactoPolitica { get; set; }
    
        public string ContactFormText { get; set; }
    
    }