How would I let this expression of mine beyond the character - (less) be accepted the + (more) as well?

Asked

Viewed 51 times

3

I have an expression on a input, using pattern, that has some rules, among them: Accept uppercase letters, lowercase, minimum of 5 characters, do not accept special characters (only accept the -).

pattern="^[A-Za-zÀ-ú0-9., -]{5,}"

I’d like to make him accept the character as well + (plus).

Go on down mine input:

<label for="razao-social-novo">Razão Social:</label>
<input type="text" placeholder="Não são permitidos caracteres especiais" pattern="^[A-Za-zÀ-ú0-9., -]{5,}" required />

  • Just an addendum here. I was indicated two great websites to perform tests in our created regex: https://regexr.com/ (this I joined and it’s really good). https://regex101.com/ (this one they said is very good too).

1 answer

3


Just add the + inside the brackets:

<input type="text" placeholder="Não são permitidos caracteres especiais"
 pattern="^[+A-Za-zÀ-ú0-9., -]{5,}" required />
            ^ aqui

Another detail, the way it is, still accepts invalid characters, because regex only checks whether the string starts with 5 or more of these characters (but can have anything else later).

Then I suggest adding also the bookmark $, which indicates the end of the string. Thus you ensure that it can only have what is specified in regex:

<input type="text" placeholder="Não são permitidos caracteres especiais"
 pattern="^[+A-Za-zÀ-ú0-9., -]{5,}$" required />
                                  ^ aqui
  • It worked right. Just one last thing, before I had tried it like this: Pattern=" [A-Za-zà-ú0-9.+ , -]{5,}" and it had also worked. My question is, what is the difference in relation to the position of the + character in your answer and in that Pattern here that I put ?

  • @No gambi, it shouldn’t make a difference. I only put it at the beginning to make it easier to see. The only one that can’t stay anywhere is the - otherwise it is interpreted as an interval (in the case of a-z, for example), but the other characters, whatever the order in which they appear

  • Yes, and if I put the +- there together, it’s a problem too. Because, I don’t know why, it’s interpreted the +- as a single character. Type: Pattern=" [A-Za-zà-ú0-9. , +-]{5,}" this would go wrong.

  • @Gambi Ué, tested here and it worked. Ah, I’m testing with the $ in the end too. But anyway, here did not go wrong...

  • Thank you very much!

Browser other questions tagged

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