简体   繁体   中英

Validating textbox on copy paste in mvc

I have a textbox that has variable maxlenght based on some condition. There are keyup and keydown events associated with the textbox. On paste my maxlenght validation fails.If "Location" is selected the type of textbox is number with maxlenght 6, for other the type is text with maxlen 11 and 15 respectively "在此处输入图片说明

$(document).on("pageinit", function (event) {
    $('input[type="text"]').on('keyup keydown', function (event) { /*Some validation*/} });
 $('input[type="number"]').on('keyup keydown', function (event) { /*Some validation*/} });

JQuery

 $(document).ready(function()  {
            var characters ;   
            $("#text").keyup(function(){
                if($('#vehicle').prop('checked')){
                characters=5;
                }
                else{
                characters=10;
                }
                if($(this).val().length > characters){
                $(this).val($(this).val().substr(0, characters));
                }
            });
        });

HTML

<input type="checkbox" id="vehicle" value="Bike">I have a bike<br>
<input type="text" id="text"/>

SEE DEMO HERE

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 -

 $(".AlphaValidateOnPaste").on('paste', function(e) { $(e.target).keyup(); }); $('.AlphaValidateOnPaste').on('keyup',function(e){ var value = $(this).val(); var i = value.length; while (i--) { var result = value.charAt(i).match(/^[a-zA-Z ]*$/); if(result == null){ $(this).val(''); alert('Only Alphabates and Spaces'); break; } } });
 <label for="name">Name <span class="required">*</span></label> <input type="text" name="employee_name" class="form-control AlphaValidateOnPaste" id="employee_name" required> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM