简体   繁体   中英

Javascript: validation for mobile number with paste option

I am working in Javascript. I am trying to make a function on the keypress event. I want to make function for validation on mobile number. I want to allow only digits in it. I also want to allow ctrl+v and ctrl+a in this but I dont want to allow V and A as characters.

I have seen many answers here but no one is purely same.

If you only care that digits are entered, as it seems from your question, this Jquery code will work.

It uses on keyup() and thus it will work on ctrl+v as well. It won't work if someone uses right-click to paste, and for that reason, you can just disable right clicking on that field.

It works by stripping off the last character of the input value if it is not a number. So if a user enters 25s or 25ss, it will get stripped down to 25.

Live Demo

The Jquery

$(document).ready(function(){
    $('#number').keyup(function(){    
        var input = this.value;
        while (isNaN(input))
        {
            input = input.substring(0,input.length-1);
            $('#number').val(input);             
        }
    });
    //disable right click on the field
    $('#number').bind("contextmenu",function(e){
        return false;
    });
});

You can use HTML5 input tags which use the pattern attribute.

<form>
    <input name="name" value="" pattern="\d+" required/>
    <input type="submit"/>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM