开发者

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?


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


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


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜