Javascript Regular Expressions match only numeric

Introduction

To allow only numeric characters (0-9) in HTML text input, use the regex /^\d*$/.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Allow Only Numeric Input in HTML Text Input Field</title>
<style>
    .success {//from  w ww .  j a v a  2 s.  c o  m
        outline: 2px solid green;
    }
    .error {
        outline: 2px solid red;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    var regex = /^\d*$/;

    $("#myInput").on("input", function(){
        var inputVal = $(this).val();

        if(regex.test(inputVal)) {
            $(this).removeClass("error").addClass("success");
        } else{
            $(this).removeClass("success").addClass("error");
        }
    });
});
</script>
</head>
<body>
    <input type="text" id="myInput">
    
</body>
</html>



PreviousNext

Related