如何将多个ID简化为多个功能?

时间:2017-08-16 09:23:13

标签: javascript datepicker asp-classic

我有以下代码检查日期的输入。我希望用户键入dd / MM / YYYY。如果用户输入dd / MM / YY,我会提醒用户。我正在为每个输入标签编写每个javascript函数。如何简化javascript函数或者我不能?

<input id="dt_join" name="dt_join" value="<%=dt_join%>" type="text" class="form-control" date-picker onblur="checkdt_join();">

<input id="dt_confirm" name="dt_confirm" value="<%=dt_confirm%>" type="text" class="form-control" datewotoday onblur="checkdt_confirm();">

<input id="dt_resign" name="dt_resign" value="<%=dt_resign%>" type="text" class="form-control" datewotoday onblur="checkdt_resign();">

function checkdt_join(){
    var input = document.getElementById("dt_join").value;
    var pattern =/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;

    if (pattern.test(input)==false){
        alert("Date format is incorrect, please key in DD/MM/YYYY");
        }   
    }

function checkdt_confirm(){
    var input = document.getElementById("dt_confirm").value;
    var pattern =/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;

    if (pattern.test(input)==false){
        alert("Date format is incorrect, please key in DD/MM/YYYY");
        }   
    }
function checkdt_resign(){
    var input = document.getElementById("dt_resign").value;
    var pattern =/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;

    if (pattern.test(input)==false){
        alert("Date format is incorrect, please key in DD/MM/YYYY");
        }   
    }

1 个答案:

答案 0 :(得分:0)

简单和脏的:在this属性中通过onblur传递输入元素。 (删除了与问题无关的属性)

function checkdt(el) {
  var input = el.value;
  var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;

  if (pattern.test(input) == false) {
    alert("Date format is incorrect, please key in DD/MM/YYYY");
  }
}
<input value="01/01/2001" type="text" onblur="checkdt(this);" />
<input value="11/11/2011" type="text" onblur="checkdt(this);" />
<input value="12/12/2012" type="text" onblur="checkdt(this);" />

清楚明确的一个:使用事件监听器

$(function() {
  $(".date-checker").blur(function checkdt() {
    var input = this.value;
    var pattern = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;

    if (pattern.test(input) == false) {
      alert("Date format is incorrect, please key in DD/MM/YYYY");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="01/01/2001" class="date-checker" type="text" />
<input value="11/11/2011" class="date-checker" type="text" />
<input value="12/12/2012" class="date-checker" type="text" />