Html <input pattern> 使用 JavaScript 处理 - 超出时失败

Html <input pattern> handling with JavaScript - fails on exceed

我在处理 HTML <input> pattern 属性时遇到问题。我想根据模式实现更改指标的颜色。在输入长度为 3 个字符之前它不会变绿,但当它超过 20 个字符时它不会再次变红。这是 HTML 代码:

<p>
    <canvas id="Circle6" width="30" height="30"></canvas>
    Imię
    <input type="text" pattern=".{3,20}" required title="3-20 characters required" id="FirstName" oninput="checkInput(id, name)" name="Circle6">
</p>

和Javascript函数:

    function checkInput(id, name) {
        var input = document.getElementById(id);
        isValid = input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0;
        var c = document.getElementById(name);
        var ctx = c.getContext("2d");
        if (isValid)
            ctx.fillStyle = "green";
        else ctx.fillStyle = "red";

        ctx.fill();
    }

isValid = input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0; 行取自 Javascript fallback for the HTML5 "pattern" attribute on <input>

编辑:圆在页面加载时绘制:

function drawCicle(elementid) {
    var c = document.getElementById(elementid);
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(15, 15, 10, 0, 2 * Math.PI);
    ctx.stroke();
}

您应该使用 .test 而不是 .search,因为后者会 return 只要您的输入超过 3 个字符(换句话说,如果您的输入字符串超过 20 个字符,您仍然会得到一个数组 returned(将被评估为 true))。

此外,您必须将正则表达式模式锚定到字符串的前面 ^ 和结尾 $,因此您只需将前者放在前面并将后者附加到模式属性值: new RegExp('^'+input.getAttribute('pattern')+'$').

function checkInput(id, name) {
    var input = document.getElementById(id),
        re = new RegExp('^'+input.getAttribute('pattern')+'$'),
        c = document.getElementById(name),
        ctx = c.getContext("2d");

    if (re.test(input.value))
        ctx.fillStyle = "green";
    else ctx.fillStyle = "red";

    ctx.fill();
}

请参阅此处 fiddle:http://jsfiddle.net/teddyrised/pmdye1y0/3/