【问题标题】:Check the value of the field in HH:MM format using ajax javascript [duplicate]使用ajax javascript检查HH:MM格式的字段值[重复]
【发布时间】:2021-01-12 16:25:53
【问题描述】:

我有一个字段 HrsBirthDate,它应该以 HH:MM 格式输入(可以是 00:01、01:19、23:44、19:34、13:12)。

所以在提交表单之前,我需要检查该值是否为上述任何一种格式,否则会抛出错误消息。

现在只有我可以检查该字段是否为空。

这是我的代码:

        $("body").on("click", "#WebGrid TBODY .Update", function () {
           var row = $(this).closest("tr");
           var employee = {};
           employee.EmployeeID = row.find(".EmployeeId").find(".label").html();
           employee.FirstName = row.find(".Name").find(".text").val();
           employee.BirthDate = row.find(".DOB").find(".text").val();
           employee.HrsBirthDate = row.find(".HrsBirthDate").find(".text").val();
 
           if (employee.FirstName != '' && employee.BirthDate != '' && employee.HrsBirthDate != '') {
               debugger;
               $("td", row).each(function () {
                   if ($(this).find(".text").length > 0) {
                       var span = $(this).find(".label");
                       var input = $(this).find(".text");
                       span.html(input.val());
                       span.show();
                       input.hide();
                   }
               });
               row.find(".Edit").show();
               row.find(".Cancel").hide();
               $(this).hide();
               $.ajax({
                   type: "POST",
                   url: "/Home/UpdateEmployee",
                   data: '{employee:' + JSON.stringify(employee) + '}',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json"
               });
           }
           else {
               alert("Please fill the details.");
               return false;
           }
       });

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    要检查字符串是否匹配 24h 格式hh:mm 范围 00:00 → 23:59),我们可以使用带有RegExp.prototype.test()的小正则表达式

    const validHHMMstring = (str) => /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(str);
    
    console.log(validHHMMstring("99:99")); // false
    console.log(validHHMMstring("24:00")); // false
    console.log(validHHMMstring("23:60")); // false
    console.log(validHHMMstring("23:59")); // true
    console.log(validHHMMstring("00:00")); // true

    并像这样使用它:

    if (validHHMMstring(employee.HrsBirthDate)) {
      // do something, is valid HH:MM
    }
    

    【讨论】:

    • 你怎么会认为这不是多次重复?
    • @HereticMonkey 我能很快找到的唯一骗子是this dupe - 而且接受的答案甚至都不正确。 this dupe中的答案都不正确
    • 然后在您选择的副本中添加正确答案,并尝试让提问者相信您的答案是正确的。与否,重复的接受答案不需要正确才能成为重复目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多