0

In my current project, I'm facing a tiny issue. There's a text field which must allow only the numbers. when the user types '.' it also must be removed.

Following is my code

validateNumber: function(value){
    var regexValidation = new RegExp("^[0-9]+$");
    return regexValidation.test(value);
},

isNumber: function(event) {
    var value = $(event.target).val();
    if (this.validateNumber(value)) {
        value = value.replace('.', '');
        $(event.target).val(value);
    } else if (value.length > 6) {
        value = value.substr(0, 6);
    }
    $(event.target).val(value);
}

The problem here is, when I type a '.' character, it accepts first time and when I typed it again then only it removes the whole text. I want it to remove it soon when it finds a '.' character. Any suggestions will be helpful

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
Mujahid
  • 1,227
  • 5
  • 32
  • 62
  • Check please this: http://stackoverflow.com/a/10003709/1540672 I think that is your answer. – brtsos Dec 21 '16 at 10:35
  • no need to replace `.` if it already matched only numbers. Post some jsfiddle link – RomanPerekhrest Dec 21 '16 at 10:35
  • JavaScript has a method to check for numbers: `isNaN`. How are you calling the function now? – putvande Dec 21 '16 at 10:41
  • If you don't want use method `isNaN` you can also use `keycode`. The code for numbers has a particular range of codes. So you don't need any replacemnts. – Reporter Dec 21 '16 at 10:47
  • @reporter the problem with the keycode is, in some Samsung devices, they key code seemed to be different, we faced that issue, that's why we dropped the idea of using keycode. Thanks for the comment – Mujahid Dec 21 '16 at 10:51
  • @Mujahid you didn't mentioned, that you working on a mobile app. ;-) – Reporter Dec 21 '16 at 10:54
  • @reporter It's very common nowadays not to mention it since using mobile devices to access internet is very common :) – Mujahid Dec 21 '16 at 10:56

1 Answers1

1

Please check this code

function removespec(str)
{
 return str.replace(/[^\d]/g,'');
}

function checkNumberval(textBox)
{
 while (textBox.value.length > 0 && isNaN(textBox.value)) {
  textBox.value = textBox.value.substring(0, textBox.value.length - 1)
 }

 textBox.value = removespec(textBox.value);

}
<input type="text" name="phone" class="form-control" id="lphone"
  onkeyup="checkNumberval(this);">
Reporter
  • 3,897
  • 5
  • 33
  • 47
Nishant Saini
  • 421
  • 3
  • 13