请参阅下面的编辑。这个问题起源于我的jquery / javascript非常差,我的验证。我已经实现了一个新的css类,它应该处理以前单个元素编辑所做的事情。同样,我的jquery验证更加动态,而且不仅仅是空字段。
我一直在开发一个基于python web框架的Web门户网站,我最近一直致力于改进相关jquery中不同表单的用户输入验证。
最初,我的jquery正在进行一次大检查,看是否有任何输入不符合验证要求,然后将输入字段的边框和输入标签更改为红色。从那以后,它已得到改进,现在对每个必填字段进行单独检查,然后将有关该字段的信息附加到将在完整验证完成后呈现的错误消息中。同样,只有未经验证的字段才会将输入字段边框和标签更改为红色,而不是像之前所有必需字段。
我现在要做的是为了我的下一个改进是更新我的jquery,希望在进行验证检查之前将css重置回基地。这样做是为了使用户可能已经校正的字段不会随红色输入字段边框和输入标签而改变。但由于它在进行提交过程时再次进行验证,因此任何无法验证的字段都将再次更改以显示红色突出显示。
除了在提交函数的开头有很多这样的东西,我能做些什么吗?
document.getElementById('elementHere').style.borderColor = "black";
document.getElementById('elementHere').style.color = "black";
$( document ).ready(function() {
//snip
$("#btnSubmit").click(function(){
$("#dlgmessage").html("Processing...");
$("#dialog-message").dialog("open");
//New Validation
var validated = "yes";
var msg = "One or more fields do not meet the validation requirements:<ul>";
if (
Clean($("#txtIndex").val()) === ""
) {
document.getElementById('txtIndex').style.borderColor = "red";
document.getElementById('txtIndex_label').style.color = "red";
validated = "no";
msg = msg + "<li>Index is required</li>";
}
if (
Clean($("#txtSourcetype").val()) === ""
) {
document.getElementById('txtSourcetype').style.borderColor = "red";
document.getElementById('txtSourcetype_label').style.color = "red";
validated = "no";
msg = msg + "<li>Sourcetype is required</li>";
}
if (
Clean($("#txtUseCase").val()) === ""
) {
document.getElementById('txtUseCase').style.borderColor = "red";
document.getElementById('txtUseCase_label').style.color = "red";
validated = "no";
msg = msg + "<li>Use Case is required</li>";
}
if (
Clean($("#txtTechOwner").val()) === ""
) {
document.getElementById('txtTechOwner').style.borderColor = "red";
document.getElementById('txtTechOwner_label').style.color = "red";
validated = "no";
msg = msg + "<li>Technical Owner is required</li>";
}
if (
Clean($("#txtExecOwner").val()) === ""
) {
document.getElementById('txtExecOwner').style.borderColor = "red";
document.getElementById('txtExecOwner_label').style.color = "red";
validated = "no";
msg = msg + "<li>Execuitve Owner is required</li>";
}
if (
Clean($("#txtAllocation").val()) === ""
) {
document.getElementById('txtAllocation').style.borderColor = "red";
document.getElementById('txtAllocation_label').style.color = "red";
validated = "no";
msg = msg + "<li>Allocation is required</li>";
}
if (
validated == "no"
) {
msg = msg + "</ul>";
$( "#dlgmessage" ).html(msg);
$( "#dialog-message" ).dialog("open");
console.log("Missing Required Fields");
document.getElementById('instructions').style.color = "red";
return;
}
//Make sure basic inputs are filled in
//if (
// Clean($("#txtIndex").val()) === "" ||
// Clean($("#txtSourcetype").val()) === "" ||
// Clean($("#txtUseCase").val()) === "" ||
// Clean($("#txtTechOwner").val()) === "" ||
// Clean($("#txtExecOwner").val()) === "" ||
// Clean($("#txtAllocation").val()) === ""
//){
// $("#dlgmessage").html("Please fill in required fields (*)");
// $("#dialog-message").dialog("open");
// document.getElementById('txtIndex').style.borderColor = "red";
// document.getElementById('txtIndex_label').style.color = "red";
// document.getElementById('txtSourcetype').style.borderColor = "red";
// document.getElementById('txtSourcetype_label').style.color = "red";
// document.getElementById('txtUseCase').style.borderColor = "red";
// document.getElementById('txtUseCase_label').style.color = "red";
// document.getElementById('txtTechOwner').style.borderColor = "red";
// document.getElementById('txtTechOwner_label').style.color = "red";
// document.getElementById('txtExecOwner').style.borderColor = "red";
// document.getElementById('txtExecOwner_label').style.color = "red";
// document.getElementById('txtAllocation').style.borderColor = "red";
// document.getElementById('txtAllocation_label').style.color = "red";
// document.getElementById('instructions').style.color = "red";
// console.log("Missing Required Fields");
//
// return;
//}
// validation passed
var postdata = {
record_id: Clean($("#txtID").val()),
splunk_index: Clean($("#txtIndex").val()),
splunk_sourcetype: Clean($("#txtSourcetype").val()),
use_case: Clean($("#txtUseCase").val()),
tech_owner: Clean($("#txtTechOwner").val()),
exec_owner: Clean($("#txtExecOwner").val()),
allocation: Clean($("#txtAllocation").val()),
comments: Clean($("#txtComments").val()),
action: "Add/Update",
page_name:location.pathname.substring(location.pathname.lastIndexOf("/") + 1)
} ;
$.post( "/submit", {data:JSON.stringify(postdata)},
function( data ) {
var msg = data;
console.log(msg);
$("#dlgmessage").html(msg);
$("#dialog-message").dialog("open");
if (
msg == "Database Update Successful" ||
msg == "Database Submission Successful"
) {
$(location).attr('href', '/protected/ci_sourcetype_usecase_list.html');
}
//return false;
},
'text'
);
});
});
我希望有一些方法可以让css'重置'但是如果我只需要明确说明每个元素以及返回的颜色是可以的。
修改
好吧,我意识到我之前的代码非常基本,可能并不理想,我花了一些时间来改进我的jquery,使其更具动态性,并且不需要在每种情况下写出if语句的shitload。我相信我的一切都很好,但是现在我可以看到我的类添加到我想要的每个html元素中,但是没有应用样式,标签和输入保持正常而不是像我预期的那样变红。当我之前使用$(field_id).parent().addClass("error");
进行此操作时,它正在工作,但我希望仅将无效字段标记为红色。
在下面找到我的更新代码
由于
$( document ).ready(function() {
$("#btnSubmit").click(function(){
$("#dlgmessage").html("Processing...");
$("#dialog-message").dialog("open");
//console.log("btnSubmit()");
var postdata = {
splunk_host: Clean($("#txtSplunkHost").val()),
ip: Clean($("#txtIP").val()),
mgmt_ip: Clean($("#txtMgmtIP").val()),
splunk_role: Clean($("#txtRole").val()),
environment: Clean($("#txtEnvironment").val()),
site: Clean($("#txtSite").val()),
splunk_class: Clean($("#txtSplunkClass").val()),
subclass: Clean($("#txtSubclass").val()),
status: Clean($("#txtStatus").val()),
platform: Clean($("#txtPlatform").val()),
spec: Clean($("#txtSpec").val()),
comments: Clean($("#txtComments").val()),
record_id: Clean($("#txtRecordID").val()),
action: "Add/Update",
page_name:location.pathname.substring(location.pathname.lastIndexOf("/") + 1)
} ;
console.log(postdata);
//New Validation
var validated = true;
var msg = "One or more fields do not meet the validation requirements:<ul>";
var fields_names = {"splunk_host": "Splunk Host", "ip": "IP Address", "mgmt_ip": "Management IP", "splunk_role": "Role", "environment": "Environment", "site": "Site", "splunk_class": "Splunk Class", "subclass": "Subclass", "status": "Status", "platform": "Platform", "spec": "Spec", "comments": "Comments", "record_id": "Record ID"};
var required_fields = ["splunk_host", "ip", "mgmt_ip", "splunk_role", "environment", "site", "splunk_class", "subclass", "status", "platform", "spec"];
var field_to_html_id = {"splunk_host": "txtSplunkHost", "ip": "txtIP", "mgmt_ip": "txtMgmtIP", "splunk_role": "txtRole", "environment": "txtEnvironment", "site": "txtSite", "splunk_class": "txtSplunkClass", "subclass": "txtSubclass", "status": "txtStatus", "platform": "txtPlatform", "spec": "txtSpec"};
var field_lengths = {"splunk_host": 255, "ip": 25, "mgmt_ip": 50, "splunk_role": 100, "environment": 25, "site": 100, "splunk_class": 100, "subclass": 100, "status": 25, "platform": 100, "spec": 100, "comments": 1000, "record_id": 100};
$.each(required_fields, function(i,l) {
var field = required_fields[i];
var field_id = "#" + field_to_html_id[l];
console.log(field_id);
if ( postdata[field] === "" ) {
msg = msg + "<li>" + fields_names[l] + " is required</li>";
validated = false;
console.log(fields_names[l] + " is blank");
$(field_id).addClass("error");
$(field_id + "_label").addClass("error");
}
else {
//console.log(fields_names[l] + " is not blank");
}
});
$.each(field_lengths, function(k,v) {
var field = k;
var length_limit = v;
var field_id = "#" + field_to_html_id[k];
if ( postdata[field].length > length_limit) {
msg = msg + "<li>" + fields_names[k] + " is limited to " + String(length_limit) + " characters</li>";
console.log(fields_names[k] + " is over the character limit of " + String(length_limit));
validated = false;
$(field_id).addClass("error");
$(field_id + "_label").addClass("error");
}
else {
//console.log(fields_names[k] + " is within the character limit");
}
});
if (validated) {
// submit when validated is true
$.post( "/submit", {data:JSON.stringify(postdata)},
function( data ) {
var msg = data;
console.log(msg);
$("#dlgmessage").html(msg);
$("#dialog-message").dialog("open");
if (
msg == "Database Update Successful" ||
msg == "Database Submission Successful"
) {
$(location).attr('href', '/protected/ci_splunk_server_list.html');
}
//return false;
},
'text'
);
}
else {
msg = msg + "</ul>";
console.log(msg);
$( "#dlgmessage" ).html(msg);
$( "#dialog-message" ).dialog("open");
return;
}
});
//---------------------------------------------------------------------------------------------------
$("#dialog-message").dialog({
modal: true,
autoOpen: false,
position: { my: "top", at: "top", of: $("#page-inner") },
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
});
/*========================================
Errors
========================================*/
.error input {
border: 2px solid red;
}
.error label {
color: red;
}
<div class="form-group">
<label id="txtSplunkHost_label">Splunk Host (*)</label>
<input class="form-control" placeholder="Splunk Host" id="txtSplunkHost" value="" maxlength="255" autofocus="">
<label id="txtIP_label">IP Address (*)</label>
<input class="form-control" placeholder="IP Address" id="txtIP" value="" maxlength="25" pattern="^[1-9]\d*$">
<label id="txtMgmtIP_label">Management IP (*)</label>
<input class="form-control" placeholder="Management IP" id="txtMgmtIP" value="" maxlength="50">
<label id="txtRole_label">Role (*)</label>
<input class="form-control" placeholder="Role" id="txtRole" value="" maxlength="100">
<label id="txtEnvironment_label">Environment (*)</label>
<input class="form-control" placeholder="Environment" id="txtEnvironment" value="" maxlength="25">
<label id="txtSite_label">Site (*)</label>
<input class="form-control" placeholder="Site" id="txtSite" value="" maxlength="100">
<label id="txtSplunkClass_label">Splunk Class (*)</label>
<input class="form-control" placeholder="Splunk Class" id="txtSplunkClass" value="" maxlength="100">
<label id="txtSubclass_label">Subclass (*)</label>
<input class="form-control" placeholder="Subclass" id="txtSubclass" value="" maxlength="100">
<label id="txtStatus_label">Status (*)</label>
<input class="form-control" placeholder="Status" id="txtStatus" value="" maxlength="25">
<label id="txtPlatform_label">Platform (*)</label>
<input class="form-control" placeholder="Platform" id="txtPlatform" value="" maxlength="100">
<label id="txtSpec_label">Spec (*)</label>
<input class="form-control" placeholder="Spec" id="txtSpec" value="" maxlength="100">
<label id="txtComments_label">Comments</label>
<input class="form-control" placeholder="Comments" id="txtComments" value="" maxlength="1000">
<input type="hidden" id="txtRecordID" value="">
</div>
<button type="button" class="btn btn-default" id="btnSubmit">Submit</button>
答案 0 :(得分:1)
由于您要求更好的实施,
以下是一种动态方法,您无需添加数百个if条件和DOM选择器。这种方法也使用推荐的css
方法,而不是应用单独的样式属性。
代码易于理解和自我解释。
$("#submit").on("click", function(e) {
//Prevent default form action
e.preventDefault();
//Add all inputs into an array
var inputs = [$("#name"), $("#address")],
is_form_valid = true;
//Validations
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].val() == "") {
inputs[i].parent().addClass("error");
inputs[i].focus();
is_form_valid = false;
break;
} else {
inputs[i].parent().removeClass("error");
}
}
//Form has no validation errors.
if (is_form_valid) {
//Do your work here...
alert("Form submitted");
}
});
.error input[type="text"] {
border: 2px solid red;
}
.error label {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name">
</div>
<div class="field">
<label for="address">Address:</label>
<input type="text" id="address">
</div>
<button id="submit" type="submit">Submit</button>
</form>
<强>更新强>
我看到你做了一些工作,使它更容易可读 :) 那里有大量的表单验证库。作为一个建议,我建议你使用其中一些而不重新发明轮子。但这是学习良好编码标准的好习惯。
您的问题css
类HTML
结构错误。我为HTML
结构添加了这些类。在您的情况下,没有包装div
。您应该使用input
课程直接访问label
和error
,如下所示。
/*========================================
Errors
========================================*/
input.error {
border: 2px solid red;
}
label.error {
color: red;
}