gal-s
10/16/2018 - 11:06 AM

Form Field Validation using jQuery & REGEX

In this example - testin 3-16 digit number

<script>
        $(document).ready(function(){
            var $regexname=/^([0-9]{3,16})$/;
            $('.number').on('keypress keydown keyup',function(){
                if (!$(this).val().match($regexname)) {
                    // there is a mismatch, hence show the error message
                    $('.emsg').removeClass('hidden');
                    $('.emsg').show();
                }
                else{
                    // else, do not display message
                    $('.emsg').addClass('hidden');
                }
            });
        });
</script>

<form>
    <label>Name
        <input class="number" type="text"  placeholder="Enter your name:" required/></label>
    <p><span class="emsg hidden">Please Enter a Valid Name</span></p>
    <input type="submit" value="Submit"/>
</form>

<style>
    emsg{
        color: red;
    }
    .hidden {
        visibility:hidden;
    }
</style>