What is regex to validate only points, numbers and commas?

Asked

Viewed 13,204 times

3

What is the regex to validate only points, numbers and commas?

2 answers

8

Would this be:

^[\d,.?!]+$
  • The ^ check from the beginning
  • The $ Czech from the end
  • The \d czech numbers
  • Anything inside of [...] will be considered, regardless of position, then can remove ? and ! if desired, as I did not know which points I wanted to add both

Javascript

Of course this will only test the string and in case your validator gives to understand that this is what you want, if you want to use with Javascript can do something like this:

function validar() {
    var meucampo1 = document.getElementById("meu-campo-1");
    var valido = /^[\d,.?!]+$/.test(meucampo1.value);
    
    alert(valido ? "Validou" : "Não validou");
}
Digite algo no campo e aperte em validar:
<input type="text" id="meu-campo-1">
<button onclick="validar()">Validar</button>

HTML5 validation

If you’re going to use the pattern="..." can apply like this:

<form action="" name="form1">
    Digite algo no campo e aperte em validar:
    <input value="" pattern="[\d,.?!]*" title="Please enter allowed characters only.">
    <button>Validar</button> 
</form>

  • 1

    In this case, the point needs to be \. since he is an element of the regex, too, from what I understand, she does not need interrogation, nor exclamation, but if she wants interrogation, she must be \?. Other than that, I imagine she also wants to match an empty string, so it would be the case to change the + for *...

  • 5

    @Felipeavelar this wrong, if inside [....] doesn’t need "escapes".

8

Would that be:

(?:\.|,|[0-9])*

Explanation:

  • \. - Dot.

  • , - Comma.

  • [0-9] - Numbers.

  • | - Indicates choice.

  • \.|,|[0-9] - Choose between a semicolon or numbers.

  • (?: ... ) - Grouping without capture.

  • * - Group repetition.

  • (?:\.|,|[0-9])* - A repetition of dots, commas and numbers.

Browser other questions tagged

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