Search code examples
jqueryvalidationcopy-pastepastenumeric

jQuery Validate Numeric After Pasting


I know how to validate a field for numeric values, but how can you validate the field if invalid characters have been pasted into the field. Often we have a numeric field, and then an action button, and the numeric field may not fire a blur event when the action button is clicked. How can you force (re)validation in this case? Do you do it again in the click event of the action button, or there there a more elegant solution?


Solution

  • I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.

    $('#txtbox').on('paste', function (e) {
        var $this = $(this);
        setTimeout(function (e) {
            if (($this.val()).match(/[^0-9]/g))
            {
                $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");                       
                setTimeout(function (e) {
                    $this.val(null);
                },2500);
            }                   
        }, 5);
    });