0

I have two text box in a form. One verifies for number only and another one for number and comma.

1st case number only.

function(textBoxObject) {
    var that = $(this),
    val = that.val();

    if (val === "" || isNaN(val)) {
      that.addClass("error");
    } else {
     that.removeClass("error");
    }
}

2nd case number and comma.

How do I handle another textbox which takes numbers and commas? And is it possible to add the logic in the first function itself?

ianaya89
  • 4,153
  • 3
  • 26
  • 34
user2950017
  • 35
  • 1
  • 11
  • You might need to take a look at [this answer][1] [1]: http://stackoverflow.com/questions/6190312/validate-currency-amount-using-regular-expressions-in-javascript – jzap Nov 12 '14 at 02:07

4 Answers4

1

I assume you treat 12,34 as illegal and 1,234 as legal. Then here's the demo

function checkNumberWithComma(textBox) {
    if ((textBox.value == 0 || textBox.value) && textBox.value.match(/^\d{0,3}(?:,\d{3})*$/)) {
        $(textBox).removeClass("error");
    }
    else {
        $(textBox).addClass("error");
    }
}

And the regular expression:

^       means start
\d{0,3} means 0-3 digits
(?:     means non-capturing group 
,
\d{3}   means 3 digits
)
*       means repeat for 0 or more times
$       means end
wander
  • 937
  • 1
  • 7
  • 15
0

You can use .indexOf() method.

something like...

if(val.indexOf(',') === -1) {
    ...your code here...
}
KaMZaTa
  • 535
  • 2
  • 9
  • 24
0

You could try and use if(val.match(/^(\d,?)*$/g))

It will allow an empty string, numbers and numbers seperated by commas. It does allow commas at the end of the string, though.

So, 1,2,3,4, 1234 and 1234, all pass, but ,12,34 and foo will fail.

AlecBrooks
  • 524
  • 4
  • 12
0

Take a look a this codepen, I don't know exactly the behaviour you want but you can try something similar.

JS

$(function(){
  function validateInput() {
      var that = $(this),
      val = that.val();
      if (that.attr('data-type') === 'number') {
        if (val === '' || isNaN(val)) that.addClass('error');
        else that.removeClass('error');
      }
      else {
        if (val.indexOf(',') === -1) that.addClass('error');
        else that.removeClass('error');
      }
  }

  $('input').change(validateInput);
});

HTML

<div>
  <label> Number
    <input type="text" data-type="number"/>
  </label>
</div>

<div>
  <label> Comma
    <input type="text"/>
  </label>
</div>
ianaya89
  • 4,153
  • 3
  • 26
  • 34