【问题标题】:Trigger the pattern attribute of input box using javascript?使用javascript触发输入框的pattern属性?
【发布时间】:2014-05-02 04:47:23
【问题描述】:

我需要使用 javascript 检查输入框的模式。我需要这样做的原因是,每次在输入框中更改某些内容时,都会通过 ajax 提交表单。所以这必须延迟,必须执行检查,如果不正确,必须停止 ajax 进程。这一切都很好,除了,我怎样才能触发模式属性?显然没有使用提交。

HTML

<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" />

编辑

我想偷懒,不想重新实现模式。例如。我想免费获得这个

See in this fiddle

这个漂亮的消息包含在输入框的标题属性中,当用户尝试提交与模式不匹配的内容时,它显然显示得非常好。

好吧,有人出于某种原因问我不了解 ajax sn-p。 btw handleUTF8Decode.php 正在解决字符集问题,然后包含实际页面。 你去:

 $.ajax({
            type: "post",
            url: "/mycompany/handleUTF8Decode.php",
            data: jform.serialize(),
            dataType: 'html',
            async: true,
            beforeSend: function () {
                $("#ajax-status").html("Processing");
            },
            success: function (data) {
            },
            error: function (xhr, status, error) {
                $("#ajax-status").html("ERROR " + "<div class='ajaxResponse'>"+data+"</div>" );
            }
        });

【问题讨论】:

  • 触发AJAX的onchange代码在哪里?
  • 这不是@tymeJV 要求的代码...
  • 如果您希望我们为您完成作业或工作,我建议您减少敌意。 This SO Thread 将把你推向正确的方向。
  • @RenéRoth 感谢您的链接,但这不是我想要的。我不想重新实现模式。如果可能的话,我想触发它​​的功能,包括标题显示错误。
  • 我还是不明白为什么你会要求on('change') 代码。这是完全基本的

标签: javascript jquery html


【解决方案1】:

pattern 没有什么可以“触发”的。您只需检查相关元素的validity

jform.find("input[pattern]").prop("validity").patternMismatch // boolean

【讨论】:

  • 这很酷,不知道这个。我将在我的问题中指定一些额外的内容以了解所有内容
  • 这是迄今为止最好的答案。谢谢你,Bergi
【解决方案2】:

更新答案

响应 OP 在下面的评论...

在漫长的工作日结束后,我很快就把它整理好了,所以我为憔悴而道歉。可以在JS Bin 上找到完整的工作示例(带有大量注释)。这个例子展示了如何使用 jQuery UI 的 datepickertooltip 小部件结合输入字段的标准 oninput 事件来创建一个动态字段,该字段无需提交表单数据即可进行客户端表单验证。

我意识到这可能不是最优雅的方式,但我没有在这个论坛中看到过建议。 话说回来,这可能是有充分理由的......

不过,这里是对框架的快速浏览——要在“行动”中看到它,您可以查看它的JS Bin page请原谅格式,我现在对 CSS 太懒了。

// I've gone ahead and removed most of the code and notes for
// brevity. See: [http://jsbin.com/wuyum/1/edit?js,output]
$(function () {
    // Internal function used to incrementally validate the user's
    // input (valid for both mm/dd/yyyy & dd/mm/yyyy formats).
    function validateInput(contents) {
        var rgx = /^(\d{1,2}(?:\/(?:\d{1,2}(?:\/(?:\d{1,4})?)?)?)?)$/;
        return rgx.test(contents);
    };

    // Internal function used to check a valid date format against
    // a valid date (e.g. 99/99/2014 is not a valid date).
    function checkDate(date) {
        return !isNaN(new Date(date).getDate());
    };

    // Create a new datepicker object and use its onSelect event to
    // run through your AJAX call...
    $('#date').datepicker({
        // onSelect will be called when the user either selects a date
        // from the widget, or uses the Return/Enter key on submission.
        onSelect: function (date) {
            // By now the date has already been validated, client-side,
            // in two-part. First the RegEx matched a mm/dd/yyyy format
            // and then we confirmed that the date wasn't erroneous with
            // checkDate(). If the user submitted an invalid date (say
            // '44/44') the widget will automatically reset the date to
            // 'today'. Alternatively, you could call checkDate() again
            // during this event -- that's really your call.

            // Execute your AJAX call
            // $.ajax() ...
        }
    }).tooltip({
        // Define a non-delegated tooltip to use as a prompt...
    }).on('input', function () {
        // Handle the forms RegExp and format validation here...
    });
});

值得注意的是datepicker的默认格式是mm/dd/yyyy。这可以很容易地更改,但是应该警告您,如果您的目标是为用户提供输入mm/dd/yyyydd/mm/yyyy 的选项,除非首先使用正在使用的格式进行验证,否则您将遇到一些问题。例如:

10/06/2014 --> October 6th 2014 (mm/dd/yyyy)
10/06/2014 --> June 10th 2014 (dd/mm/yyyy)

希望对你有所帮助。


原答案

从您的 RegEx 模式来看,您似乎正在尝试根据标准日期格式 mm/dd/yyyy 验证该字段。

如果是这种情况,并且您想在每次更改字段时验证格式,我建议使用jQuery UIDatepicker 小部件——利用datepickers onSelect 事件。像这样:

// where #date is the id of <input id="date" type="text"/>
$('#date').datepicker({
    onSelect: function(date) {
        // $.ajax() here
    }
});

或者,您可以在 input 字段的 onchange 事件中管理 RegEx 验证和 AJAX 调用。

// obviously you'd want to be more specific than simply grabbing the first
// input element found.
document.getElementsByTagName('input')[0].onchange = function (e) { ... };

最后,您可以查看 HTML5 及其对 date type 属性的实现。

【讨论】:

  • 即使手动输入日期也会触发onSelect吗?
  • @bartlb - 你确定不是标准日期格式dd/mm/yyyy?世界上更多的人使用这种格式而不是 m/d/y
  • @StephenP 完全有效的点。为我辩护,我只能从 RegEx 中假设这么多。
  • @Toskan - 当用户按下 Return/Enter 键时会触发 onSelect 事件。我将在我的答案中添加一个更详细的示例来澄清。
  • 我会接受这个答案,即使它不能解决原来的问题。顺便说一句,我喜欢 checkDate 功能,不知道它们存在。我也忘记了 jquery 工具提示的实现
【解决方案3】:

在用户仍在更改值时显示错误消息并不是最佳模式。只需使用输入类型=“日期”并绑定到“输入”事件。只有在没有类型不匹配的情况下才会触发该类型的输入事件。

演示:http://jsfiddle.net/trixta/8e95N/

$(function(){
    $('input[type="date"]').on('input', function(){
        //your ajax
        console.log($.prop(this, 'value'));
    });
});

【讨论】:

  • 好例子,想获取HTML5模式属性的值,用同样的思路。
猜你喜欢
  • 1970-01-01
  • 2016-10-23
  • 2013-09-09
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
相关资源
最近更新 更多