DataAnnotations problem in string [] fields

-1

I need an help to validate a string[] field, since whenever I send this empty field, it returns error, even though it is in the correct format:

The field is this:

    [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "E-mail está em um formato inválido.")]
    [Display(Name = "E-mail")]
    public string[] Email { get; set; }

This field will not always be filled, but every time you send it blank null , it will generate the error E-mail está em um formato inválido. . It will be possible to send 1 to n emails, I needed that every email that was sent was validated by the regular expression, would you know to help me?

    
asked by anonymous 19.09.2018 / 21:19

3 answers

1

If you want to validate a collection of values I would recommend you break and another object and put the validation on the element, see the example below

[Display(Name = "E-mails")]       
public IEnumerable<EmailViewModel> Emails { get; set; }

public class EmailViewModel
{
    [Display(Name = "E-mail")]
    [EmailAddress(ErrorMessage = "E-mail está em um formato inválido.")]
    public string Email { get; set; }
}

Now if you can not or do not want to change the data input form, you could implement IValidatableObject in your view model. See the example below, but I still recommend the first option to respect the recommendations of ASP.Net MVC and not deprive it of all the facilities that the framework provides. By doing so you will be giving up the scaffolding utilities and validators that are already available to you.

public class CadastroViewModel : IValidatableObject
{

    [Display(Name = "E-mail")]        
    public string[] Email { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Email != null)
        {
            foreach (string entrada in Email)
            {
                Regex regex = new Regex(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$");

                if (entrada != null && !regex.IsMatch(entrada))
                    yield return new ValidationResult(string.Format("{0} não é um e-mail válido.", entrada, new[] { nameof(Email) }));

            }
        }

    }
}
    
19.09.2018 / 21:37
0

Change your regex to accept empty:

^$|^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$
    
19.09.2018 / 21:36
0

As the above friends help did not work for me, I created a Validation folder and inside it I created the CustomAnnotations.cs class with the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace EasySistema.Validation
{
    public class CustomAnnotations
    {
     [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
     public class EmailArrayValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string[] array = value as string[];

            Regex regex = new Regex(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$");

            if (array != null)
            {
                foreach (var email in array)
                {
                    if (email != null)
                    {
                        if (!regex.IsMatch(email))
                        {
                            return new ValidationResult("Email inválido.");
                        }
                    }
                }

                return ValidationResult.Success;
            }

            return base.IsValid(value, validationContext);
        }

    }

}

And within my AddClientViewModels , I use it this way:

[EmailArrayValidation]
[Display(Name = "E-mail")]
public string[] Email { get; set; }

So all emails within the array will be validated, and if there is an invalid email, the error will be returned.

I hope I have helped.

    
19.09.2018 / 22:24