Mohammad Malek
Mohammad Malek

Reputation: 634

only number and "."(DOT) allowed in input

I want to allow only "." and a number of other characters or etc not allowed.

Following code is working properly but it's allowing "."

html and js

     <input type="text" class="form-control" id="PhoneNo" name="PhoneNo" minlength="10" maxlength="12" placeholder="Enter Phone No">

     $('#PhoneNo').keyup(function()
        {
            if (/\D/g.test(this.value))
            {
              this.value = this.value.replace(/\D/g, '');
            }
        });

Upvotes: 1

Views: 142

Answers (3)

Aniket G
Aniket G

Reputation: 3512

Use the following code. If it does not match with the regex (which only matches numbers and dot), it will remove the last value.

Every time you press a key (not release it, so the value isn't in the input), the .keypress() function activates. That says that if the value doesn't match the regex, remove the last character. This works, except since it's on keypress, and the character counts as "being typed" when you release the key (on .keyup(), you can just add a .keyup() function to counteract that.

let pattern = new RegExp("^[0-9.]+$");

$("#PhoneNo").keypress(function() {
  if (!pattern.test($(this).val())) {
    $(this).val($(this).val().slice(0, -1));
  }
});

$("#PhoneNo").keyup(function() {
  if (!pattern.test($(this).val())) {
    $(this).val($(this).val().slice(0, -1));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="PhoneNo" name="PhoneNo" minlength="10" maxlength="12" placeholder="Enter Phone No">

Upvotes: 2

Abdul Rehman Sheikh
Abdul Rehman Sheikh

Reputation: 939

Try this as well:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <input type="text" class="form-control" id="PhoneNo" name="PhoneNo" minlength="10" maxlength="12" placeholder="Enter Phone No" />

        <script>
            $("#PhoneNo").keyup(function (e) {
                checkNumbersOnly($(this));
            });

            function checkNumbersOnly(myfield)
            {
                if (/[^\d\.]/g.test(myfield.val()))
                {
                    myfield.val(myfield.val().replace(/[^\d\.]/g, ''));
                }
            }
        </script>

    </body>
</html>

Upvotes: 1

Vlam
Vlam

Reputation: 1798

Try the below:

if (/[^\d\.]/g.test(this.value))
{
    this.value = this.value.replace(/[^\d\.]/g, '');
}

Upvotes: 1

Related Questions