在textarea中键入时,JavaScript表单验证消息不断触发

时间:2019-04-01 20:56:32

标签: javascript jquery html-form

编辑:我正在使用Symfony表单创建表单,但是不确定是否相关

我正在验证textarea元素以仅检查空白,如果没有字符则抛出错误。该检查有效,并由“提交”按钮触发。但是,如果触发了验证消息,即使它不是空格,每次输入时该消息仍会出现。

这是我的JS文件

jQuery(document).ready(function () {
//the submit button is #announcement_create_save
    $('#announcement_create_save').click(function () {
        var content = $('#announcement_create_content').val();
// The regex which checks if the field only has whitespace
        if (!(/.*\S+.*/.test(content))) {
            document.getElementById('announcement_create_content').setCustomValidity('Please fill out this field.');
        }
        else {
            document.getElementById('announcement_create_content').setCustomValidity("");
        }
    })
});



HTML

<form name="announcement_create" method="post">
                        <div class="announcement-card-body">
                            <label for="announcementText" class="content-label">Announcement (Supports Markdown)</label>
                            <textarea id="announcement_create_content" name="announcement_create[content]" required="required" class="form-control announcement-text" rows="5" name="content" maxlength="2000"></textarea>
                        </div>
                    </div>
                </div>
            <div class="card-footer border-0 bg-white pt-0">
                <div>
                    <button type="submit" id="announcement_create_save" name="announcement_create[save]" class="btn btn-primary"><span class="fas fa-check"></span>  Post announcement </button>
                    <button type="button" class="btn btn-light" data-dismiss="modal" aria-label="Close">Cancel
                    </button>
                </div>
            </div>

    </form>

1 个答案:

答案 0 :(得分:0)

触发验证后,将显示验证弹出通知几秒钟
enter image description here
等待此验证消息被触发,然后尝试输入文本区域。

警报不会每次触发时都由于JavaScript加载几秒而延迟,因此每次触发。