Validate html text input as it's typed

前端 未结 9 668
再見小時候
再見小時候 2020-11-27 16:36

What\'s the best way of validating an HTML text input as it\'s typed? All ways I know of doing it has some drawbacks:

  1. Using $.keypress you only

9条回答
  •  醉梦人生
    2020-11-27 17:17

    let that=this;
    
    $(this.element).find("input").keypress(function(e) {
                   let character = String.fromCharCode(e.keyCode);
    
                   let newValue =  this.value.substring(0,this.selectionStart) + character + this.value.substring(this.selectionEnd, String(this.value).length);
    
    
                   if (!that.isFormatValid(newValue, that.getdecimalPoints())) {
                         e.preventDefault();
                         e.stopPropagation();
                         return false;
                  }
    
                  return true;
            });
    
    
            $(this.element).find("input").bind({
                  paste: function() {
                         let _this = this;
    
                         setTimeout( function() {
                               let decimals = that.getdecimalPoints();
                               if (!that.isFormatValid($(_this).val(), decimals)) {                        
                                             $(_this).val('');                        
                               }
                         }, 0);                                                                                                  
                      }
               });
    

提交回复
热议问题