我正在尝试为我正在重写的数据表编辑器实现客户端输入验证。表单是动态创建的,然后添加到引导模式。
我在添加 <pattern>
时遇到了问题和/或 required
根本不会产生任何附加功能。表单只接受输入并提交,我很困惑为什么会这样。
编辑: 我已将相关代码添加到 plunkr
我现在已经添加了完整的项目。具体来说,问题与 _openEditModal 函数和 _openAddModal 函数有关,我在其中动态生成表单并添加 pattern='patternVariable'
.
这个例子的模式(但是无论我使用什么模式它都不起作用):
^[a-zA-Z0-9\.]+$
创建表单:
var data = "";
data += "<form name='altEditor-form' role='form'>";
for(var j = 0; j < columnDefs.length; j++){
data += "<div class='form-group'><div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:7px;'><label for='" + columnDefs[j].title + "'>" + columnDefs[j].title + ":</label></div><div class='col-sm-9 col-md-9 col-lg-9'>";
if(columnTypes[j].type.includes("text")){
data += "<input type='" + columnTypes[j].type + "' id='" + columnDefs[j].title + "' pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required name='" + columnDefs[j].title + "' placeholder='" + columnDefs[j].title + "' style='overflow:hidden' class='form-control form-control-sm' value='" + adata.data()[0][newaData[j].name] + "'>";
}
if(...){...}
data +="</div><div style='clear:both;'></div></div>";
}
data += "</form>";
如你所见,我是这样添加标签的:
pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required ...
模态:
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Edit Record');
$('#altEditor-modal').find('.modal-body').html(data);
$('#altEditor-modal').find('.modal-footer').html("<button type='button' data-content='remove' class='btn btn-default' data-dismiss='modal'>Close</button>\
<input type='submit' data-content='remove' class='btn btn-primary' id='editRowBtn'>Save Changes</input>");
我确保按钮有 type='submit'
正如我所读到的,这就是触发模式检查的原因。
editRowBtn代码:
$(document).on('click', '#editRowBtn', function(e)
{
e.preventDefault();
e.stopPropagation();
that._editRowData();
});
为了确保我的代码确实将属性添加到输入中,我检查了控制台:
非常感谢任何帮助或建议,因为我有点被困在这里。
最佳答案
阅读您的示例有点困难(plunkr 会更好 :)),但据我所知,您已将提交按钮放在表单之外。
那行不通,因为按钮不知道它提交的是什么。
尝试将提交按钮放在表单中。
或者,尝试在提交按钮上使用 form
属性,它应该引用表单 ID。我自己从未使用过它,但根据 MDN,它是 HTML5 规范的一部分。
Form attribute description from MDN:
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place elements anywhere within a document, not just as descendants of their form elements. An input can only be associated with one form.
关于javascript - <pattern> & required 不适用于动态创建的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39014412/