2017-09-20 3 views
-1

下記の編集を参照してください。私の検証のための非常に貧しいjquery/javascriptを持っていた間に質問が起きました。私はそれ以来、個々の要素の編集が以前に行っていたことに気をつけなければならない新しいCSSクラスを実装しました。また、jqueryの検証は、空のフィールドだけでなく、よりダイナミックなものです。jqueryを使用してCSSを変更すると、.adClassだけでなく、.parent().addClassも使用できます


私はPythonのWebフレームワークのCherryPyに基づいてWebポータルに取り組んできた、と私は最近、関連jqueryの内の異なる形式のユーザー入力の検証を改善することに取り組んできました。

元々、私のjqueryは入力が検証要件を満たさず、入力フィールドと入力ラベルの境界を赤に変更した場合、大きなチェックを1回行っていました。以後、各必須フィールドの個別チェックを行うように改良されました。その後、完全な検証が完了した後にレンダリングされるエラーメッセージにそのフィールドに関する情報が追加されます。また、妥当性検査されていないフィールドには、入力フィールドの罫線と、以前のようなすべての必須フィールドの代わりにラベルが赤に変更されています。

私の次の改善のために今行っているのは、妥当性検査を行う前にjssを更新して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だけで「リセット」することができることをいくつかの方法があります期待していますが、私はちょうど、明示的に各要素を述べるために、どのような色が戻ってそれに行く必要がある場合大丈夫。


EDIT:

さて、私は私のコードは前に理想的な非常に基本的な、おそらくありませんでした、私はよりダイナミックであることを私のjqueryのを改善して取り組んでいくつかの時間を費やしたとshitloadを必要としていないことに気づきましたすべての条件で書き出されたif文の数。私はすべてがうまくいっていると信じていますが、私のクラスが私の望む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"> 
 
\t <label id="txtSplunkHost_label">Splunk Host (*)</label> 
 
\t <input class="form-control" placeholder="Splunk Host" id="txtSplunkHost" value="" maxlength="255" autofocus=""> 
 
\t <label id="txtIP_label">IP Address (*)</label> 
 
\t <input class="form-control" placeholder="IP Address" id="txtIP" value="" maxlength="25" pattern="^[1-9]\d*$"> 
 
\t <label id="txtMgmtIP_label">Management IP (*)</label> 
 
\t <input class="form-control" placeholder="Management IP" id="txtMgmtIP" value="" maxlength="50"> 
 
\t <label id="txtRole_label">Role (*)</label> 
 
\t <input class="form-control" placeholder="Role" id="txtRole" value="" maxlength="100"> 
 
\t <label id="txtEnvironment_label">Environment (*)</label> 
 
\t <input class="form-control" placeholder="Environment" id="txtEnvironment" value="" maxlength="25"> 
 
\t <label id="txtSite_label">Site (*)</label> 
 
\t <input class="form-control" placeholder="Site" id="txtSite" value="" maxlength="100"> 
 
\t <label id="txtSplunkClass_label">Splunk Class (*)</label> 
 
\t <input class="form-control" placeholder="Splunk Class" id="txtSplunkClass" value="" maxlength="100"> 
 
\t <label id="txtSubclass_label">Subclass (*)</label> 
 
\t <input class="form-control" placeholder="Subclass" id="txtSubclass" value="" maxlength="100"> 
 
\t <label id="txtStatus_label">Status (*)</label> 
 
\t <input class="form-control" placeholder="Status" id="txtStatus" value="" maxlength="25"> 
 
\t <label id="txtPlatform_label">Platform (*)</label> 
 
\t <input class="form-control" placeholder="Platform" id="txtPlatform" value="" maxlength="100"> 
 
\t <label id="txtSpec_label">Spec (*)</label> 
 
\t <input class="form-control" placeholder="Spec" id="txtSpec" value="" maxlength="100"> 
 
\t <label id="txtComments_label">Comments</label> 
 
\t <input class="form-control" placeholder="Comments" id="txtComments" value="" maxlength="1000"> 
 
\t <input type="hidden" id="txtRecordID" value=""> 
 
</div> 
 
<button type="button" class="btn btn-default" id="btnSubmit">Submit</button>

+0

クラスはとても素敵です.....削除するクラスとループを持つすべての要素を選択してください。 – epascarello

+0

オハイオ州マイ・マッド・インフォメーション・オン・ザ・ミー・イン・ザ・ウェイ –

+0

@TheCodesee申し訳ありません?私は通っていようとしていました... – stephen

答えて

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>

UPDATE

私はあなたがそれがより読める:) フォーム検証ライブラリのトンがそこにあります作るためにいくつかの作業を行っている参照してください。アドバイスとして、ホイールを再発明せずにそれらのいくつかを使用することをお勧めします。しかし、これは良いコーディング標準を学ぶ良い習慣です。

あなたの問題はcss構造のHTMLクラスで問題があります。それらのクラスは私のHTML構造のために私によって追加されました。あなたの場合、ラッパーはありませんdiverrorクラスには、inputlabelに直接アクセスする必要があります。

/*======================================== 
Errors 
========================================*/ 
input.error { 
    border: 2px solid red; 
} 
label.error { 
    color: red; 
} 
+0

元の投稿から自分のコードを更新するために私が行ったいくつかの事柄を投稿しました。クラスははるかに良く機能しますが、クラスが追加されていますが、無効な要素にのみ追加しようとしているので、スタイルはページに表示されません。 – stephen

+0

ありがとうございました!それはまさに私が探していたものでした。私はまだかなりCSSとJavaScript/jQueryに慣れていますので、あなたの助けは大いに感謝します。私が探していたのとまったく同じように動作しています。標準的な検証ライブラリは、時間と労力を節約してくれました。 – stephen

関連する問題