how to validate for name not to receive numbers or special characters c#

Asked

Viewed 36 times

0

How do I validate the name attribute where it does not allow numbers or special characters ?

I did so but it’s not working

[Required(ErrorMessage = "O campo nome é obrigatório!", AllowEmptyStrings = false)]
[MaxLength(50, ErrorMessage = "Limite máximo de 50 caracteres e limite minimo de 2 caracteres")]
[MinLength(2)]
[RegularExpression(@"^[a-zA-Z''-'\s]{2,50}+$", ErrorMessage ="Números e caracteres especiais não são permitidos no nome.")]
public string Nome { get; set; }

1 answer

0

This expression is invalid, and it looks like you tried to include a character limit in it, something that doesn’t make much sense since you already use the attributes MaxLength and MinLength.

Try using this expression to allow only spaces and letters.

@"^[a-zA-Z\s]+$"

Now to validate the properties, you use DataAnnotations.

Follows a method that makes a complete validation.

public static IEnumerable<ValidationResult> GetErrors(object model)
{
   var result = new List<ValidationResult>();
   var context = new ValidationContext(model, null, null);
   Validator.TryValidateObject(model, context, result, true);
   return result;
}

Where the parameter model would be your class.

This does not prevent the value from being assigned to the property, it only checks whether your model class is valid or not and reports errors as you set them in the attributes.

I suggest you see that post on data validation with Dataannotations

Browser other questions tagged

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