2

HTML

<input type="number" required="" pattern="\d*" id="mobile">

jQuery

var letters = /^[0-9]+$/;
var mobile_backup="";
$(document).ready(function(){
    $("#mobile").on("input", function(){
        var mobile_value=$(this).val();
        if(mobile_value==="")
        {
            mobile_backup=mobile_value;
        }
        else if(mobile_value.match(letters)===null){
            $(this).val(mobile_backup);
        }
        else{
            mobile_backup=mobile_value;
        }
    });
});

Current solution works in all devices (desktop, mobile, tablet). Is there any efficient approach available such that it works in all devices?

I know I can use a pattern for number. But I don't want an alert. I just want to allow the numbers without a dot.

1
  • var letters = /^[0-9]+$/; is very confusing! Commented Aug 30, 2020 at 11:08

2 Answers 2

2

Use pattern attribute to add regex expression in html tag. Try below code:

<form action="home_page.php">
    <label for="roll_no">Roll Number:</label>
    <input type="number" id="roll" name="roll" pattern="^[\d]+$"  title="Write your roll number"><br><br>
    <input type="submit">
</form>

Note :

  1. The pattern attribute of the input tag is not supported in Safari 10 (or earlier).
  2. Validation of pattern attribute will not prevent from writing in the field but it will prevent from submitting form.
Sign up to request clarification or add additional context in comments.

3 Comments

Already mentioned. "I know I can use a pattern for number."
Why do you put \d in a character class, it doesn't make sense.
@Toto that is used to open only numeric keypad in some devices. For me, on the iPhone, I have used it to open the numeric keypad.
0

try step="any" This allows a decimal point

1 Comment

I want without a decimal point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.