Dataannotations problem in string fields[]

Asked

Viewed 121 times

-1

I need help validating a field string[], because whenever I send this empty field, it returns error, even if it is in the correct format:

This is the field:

    [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 in, but whenever I send it blank null, it generates the error E-mail está em um formato inválido.. It will be possible to send 1 to n emails, I needed every email that was sent, validated by regular expression, would know how to help me ??

  • You managed to solve your problem?

3 answers

1

If you want to validate a collection of values I would recommend you break and another object and put the validation in 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’t or don’t want to change the form of data entry, you could implement the IValidatableObject in your model view. See the example below, but I still recommend the first option to respect the recommendations of ASP.Net MVC and not deprive you of all the facilities that the framework provides. Doing so you will be giving up the utilities of scaffolding 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) }));

            }
        }

    }
}

0

Change your regex to accept voids:

^$|^(([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}$

0


as the help of the above friends didn’t work for me, I created a folder Validation and within it I created the class CustomAnnotations.cswith 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 inside of mine AddClientViewModels, use in this way:

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

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

I hope I’ve helped.

  • you wouldn’t need to override Validationresult... I wouldn’t recommend it at all, take a look at the Validate() of IValidatableObject

  • But if I don’t override I get an error, oculta o membro herdado "valor", para que o membro atual substitua essa implementação, adicione a palavra-chave override. Caso contrário adicione a palavra chave-chave new

  • see the edition of my reply with the Validate()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.