Validate only one comma in input type ="text"

Asked

Viewed 451 times

4

The problem I’m facing is that I can’t let the user type more than one comma into input (I am using ASP.NET with Behind in C#), but also I cannot use the input type="number" because the version of the framework I am using does not let.

I tried some things with Javascript but did not succeed. Follow the code of input:

function SomenteNumero(e) {
            var tecla = (window.event) ? event.keyCode : e.which;
            if ((tecla > 47 && tecla < 58)) return true;
            else {
                if (tecla == 8 || tecla == 0 || tecla == 44 || tecla == 13) return true;
                else return false;
            }
        }
        
        var input = document.getElementById('NR_PESO');
        var oldVal = '';
        input.addEventListener('keyup', function () {
            var parts = this.value.split(',');
            if (parts && parts[1] && parts[1].length > 3) this.value = oldVal;
            oldVal = this.value;
        });
        
        
<input type="text" class="form-control" runat="server" maxlength="11" ID="NR_PESO" onkeypress='return SomenteNumero(event)' placeholder="XXXXXXX,XXX">

I am saving this information in the Mysql database as decimal(10,3) so I need only three houses after the comma and only one comma (always has the client smart enough to put a '123,3,43' or '123,343'. I accept jQuery too.

2 answers

3


You can check if the string contains more than 1 comma with .match(/,/g). If so, you keep only the first and eliminate the others using .substring() to take part of the string and make a replace to eliminate excess commas, if any.

Only that I suggest using the event input instead of keyup, because this prevents the user from being able to paste an invalid value using only the mouse, since the keyup is only fired using the keyboard. Already the event input triggers any change in the field.

Would look like this:

function SomenteNumero(e) {

   var tecla = (window.event) ? event.keyCode : e.which;
   if ((tecla > 47 && tecla < 58)) return true;
   else {
      if (tecla == 8 || tecla == 0 || tecla == 44 || tecla == 13) return true;
      else return false;
   }
}

var input = document.getElementById('NR_PESO');
input.addEventListener('input', function () {

   var v = this.value;
   var m = v.match(/,/g);

   if(m && m.length > 1){
      this.value = v.substring(0, v.indexOf(",")+1)
      + v.substring(v.indexOf(",")+1).replace(/,/g, '');
   }

});
<input type="text" class="form-control" runat="server" maxlength="11" ID="NR_PESO" onkeypress='return SomenteNumero(event)' placeholder="XXXXXXX,XXX">

2

An alternative is to use the attribute pattern, containing a regular expression that validates the format (I removed some attributes from the input in this example, just to be more succinct):

/* mudar a cor quando o texto for inválido */
input { color: black; }
input:invalid { color: red; }
<form>
  <input type="text" maxlength="11" pattern="^\d{1,7}(,\d{1,3})?$" placeholder="XXXXXXX,XXX" required>
  <input type="submit" value="ok">
</form>

I based myself on placeholder XXXXXXX,XXX, which says it can have up to 7 digits before the comma, and up to 3 digits after.

The regex uses the markers ^ and $, which indicate respectively the beginning and end of the string. So I guarantee that the input can only have what is in regex.

Then there’s the shortcut \d, which corresponds to any digit of 0 to 9. Then I use the quantifier {1,7} (at least 1 and at most 7 occurrences). That is, I can have 1 to 7 digits.

Then there’s the comma and \d{1,3} (one to 3 digits). I group that in parentheses and then put the ?, that makes that stretch optional (so the comma followed by digits is optional).

If the comma and numbers after it are mandatory, just change to ^\d{1,7},\d{1,3}$.


If the entered value is not in the given format, the form is not submitted (try to enter an invalid value and then click on "ok"). In this case a message is displayed default browser, but if you want, you can customize it:

let input = document.getElementById('NR_PESO');
input.addEventListener('input', () => {
    input.setCustomValidity('');
    input.checkValidity();
});
input.addEventListener('invalid', () => {
    input.setCustomValidity('Digite um número válido');
});
/* mudar a cor quando o texto for inválido */
input { color: black; }
input:invalid { color: red; }
<form>
  <input type="text" ID="NR_PESO" maxlength="11" pattern="^\d{1,7}(,\d{1,3})?$" placeholder="XXXXXXX,XXX"  required>
  <input type="submit" value="ok">
</form>

This solution does not prevent the user from entering an invalid value, it only prevents the form from being submitted if the value is not valid.

Remember that this only validates what was filled in the form, but nothing prevents the user from sending invalid data by other means. So don’t forget to validate this information on the server as well, before trying to record them in the bank.

Browser other questions tagged

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