C# How do I prevent composite name from saving more than one space?

Asked

Viewed 45 times

-1

This is my validation:

[Required(ErrorMessage = "O nome completo é obrigatório.", AllowEmptyStrings = false)]
[RegularExpression(@"^[a-zA-ZáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ''-'\s]*[a-zA-ZáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ]+$", ErrorMessage = "Números e caracteres especiais não são permitidos no nome.")]
[StringLength(50, MinimumLength = 1, ErrorMessage = "Limite máximo de 50 caracteres e limite minimo de 1 caracteres")]
public string Nome { get; set; }

But in the results it saves for example

Ana julia

The problem is you’re saving too:

Ana      julia

That is, it is allowing many spaces, wanted a solution that left only one space.

  • because you don’t include in regex for it to filter more than two spaces?

  • how ? does it friend

  • Take off the \s from within the brackets, and leave only one space between the sequences of letters: ^[a-zA-ZáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ''-']+( [a-zA-ZáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ]+)*$ - of course she’s still a naive regex, because she accepts names that start with Ç, for example. A more precise regex, however, would be extremely complex, then perhaps it is better to create a custom attribute

  • thanks for the tip, but the regex didn’t work

1 answer

0

You can always do it this way. Having a private string to store the value, and when doing the set immediately remove the extra spaces.

    private string _name;

    [Required(ErrorMessage = "O nome completo é obrigatório.", AllowEmptyStrings = false)]
    [StringLength(50, MinimumLength = 1, ErrorMessage = "Limite máximo de 50 caracteres e limite minimo de 1 caracteres")]
    public string Name 
    { 
        get
        {
            return _name;
        }
        set
        {
            if (_name != null &&_name.Equals(value))
            {
                return;
            }
            _name = Regex.Replace(value, @"\s+", " ");
        }
    }

Browser other questions tagged

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