Mark Richman
Mark Richman

Reputation: 29710

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?

Upvotes: 0

Views: 3824

Answers (3)

Sayan Sadhukhan
Sayan Sadhukhan

Reputation: 1

I used paste event to trigger keyup event because only using paste event I can somehow get the input but I couldn't manipulate the input given. Here's how I found a way (btw I used this for alphabet validation but you can use input type = "number" also to validate number)-

$(".NumberValidateOnPaste").on('paste', function(e) {
  $(e.target).keyup();
});

$('.NumberValidateOnPaste').on('keyup',function(e){
    var value = $(this).val();
    var result = value.match(/^\d*$/);
    
    if(result == null){
      $(this).val('');
    }
    
});
<label for="Pin Code">Pin Code</label>
                <input type="text" name="pin_code" class="form-control NumberValidateOnPaste">
                
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Upvotes: 0

Prateju Patil
Prateju Patil

Reputation: 90

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);
});

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Not really answering your question about pasting but offering an alternative: you could subscribe for the submit handler of the form and perform the validation there. Even more elegant is to use the jquery validation plugin which will do the job of subscribing for you so that you only need to define the rules and error messages:

$(function() {
    $('#myform').validate({
        rules: {
            someFieldName: {
                required: true,
                number: true
            }
        },
        messages: {
            someFieldName: {
                required: 'please enter a value',
                number: 'please enter a valid number'
            }
        }
    });
});

Upvotes: 3

Related Questions