-2
I need to check with regex so that only letters and numbers are allowed. The other characters such as ,.-*&%$#@; among others cannot be accepted. In the regex below, I’m able to validate it! I’m just having problems with white spaces. In the regex below, it can validate whitespace if I type at least one letter or number. Ex: 1(space) or (space)A. The problem occurs when I type only spaces and do not type letters or numbers, the regex below does not recognize them. I need to improve the regex below, so that it validates when I type only (blanks)and not accept them, regardless of the amount.
protected void ValidarCodigoControle()
{
RuleFor(p => p.CodigoControle)
.NotEqual("0").WithMessage("O Código de Controle é inválido.")
.MaximumLength(15).WithMessage("O Código de Controle deve ter no máximo 15 caracteres.")
.Must(TextoHelper.NaoELetraNemNumeroNemEspaco).WithMessage("O Campo Código de Controle deve possuir apenas letras ou números.");
}
public static bool NaoELetraNemNumeroNemEspaco(string texto)
{
var rg = new Regex(@"^[a-zA-Z0-9]+$");
return !string.IsNullOrEmpty(texto) ? rg.Match(texto).Success : true;
}
How do I do it?
Thank you :)
To see if there are spaces in the beginning, middle or end, nor need regex, use
Contains
is enough. But if regex should allow only letters and numbers, then it will not allow spaces. So I don’t understand what you need...– hkotsubo
In fact, its current regex already works, as it does not accept spaces: https://ideone.com/EhBxPK
– hkotsubo
@hkotsubo this regex you have problems she, IE, has differences in fact it forces be a way, finally the question ta confused a little.
– novic
@Virgilionovic In my comment above, the ideone link is an example in C# with the same regex as the question. And it doesn’t allow spaces, which by the comments I understood is what he wants. The only detail is that this regex requires at least one number (because of the
\d+
) but the issue of not accepting space already does. Anyway, I still do not understand what the question actually wants, because from what I understand the regex already works...– hkotsubo
@hkotsubo True, Master JR tries to edit the question and if possible put examples of what can and cannot be accepted.
– Wictor Chaves
Try posting the place where you are validating, see that even if you have more spaces it works https://dotnetfiddle.net/1kIgHz
– Wictor Chaves
Yes @hkotsubo I understand, I’m just saying that by his question is confused understand, how complicated it is to understand what he wants, so much that there is no right answer for him ... complicated.
– novic
@Virgilionovic, I edited the question...
– Master JR
I believe that the problem is not the regex but where you are validating.
– Wictor Chaves
@ Wictor Keys, I am using Fluentvalidation and calling a function to validate with regex. I will post the source.
– Master JR