编辑:我正在使用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>