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

0

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

    
asked by anonymous 03.10.2017 / 19:12

2 answers

7

It would be this:

^[\d,.?!]+$
  • O% with% checked from the start
  • %% checked from the end
  • O% with% checks numbers
  • Everything within ^ will be considered, regardless of position, so you can remove the? and ! if you wish, as I did not know which points I wanted, I added both

JavaScript

Of course this will only test the string and in case your validate implies that this is what you want, if you want to use it with JavaScript you 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 use $ you can do 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>
    
03.10.2017 / 19:16
5

It would be this:

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

Explanation:

  • \. - Point.

  • , - Comma.

  • [0-9] - Numbers.

  • | - Indicates choice.

  • \.|,|[0-9] - Choose between periods, commas, or numbers.

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

  • * - Group repetition.

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

03.10.2017 / 19:19