How to auto format textbox inputs

后端 未结 4 1428
野性不改
野性不改 2020-12-21 23:36

   
      
   <         


        
4条回答
  •  暖寄归人
    2020-12-21 23:47

    I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.

    // Example: mm/dd/yy or yy-mm-dd
    var format = $(".ui-datepicker").datepicker("option", "dateFormat");
    
    var match = new RegExp(format
        .replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
        .replace(/mm|dd/g, "\\d{2}")
        .replace(/yy/g, "\\d{4}"));
    var replace = "$1/$2/$3$4"
        .replace(/\//g, format.match(/\W/));
    
    function doFormat(target)
    {
        target.value = target.value
            .replace(/(^|\W)(?=\d\W)/g, "$10")   // padding
            .replace(match, replace)             // fields
            .replace(/(\W)+/g, "$1");            // remove repeats
    }
    

    https://jsfiddle.net/4msunL6k/

提交回复
热议问题