2017-09-13 41 views
-1

我試圖在提交表單時顯示錯誤消息,當單選按鈕被選中true並且輸入框爲空時,出於某種原因失敗。任何建議表示讚賞!驗證基於無線電輸入和顯示錯誤消息的輸入字段

<div class="row col-lg-offset-2 top-buffer"> 
<h4> 
    <strong> 
     <span>Is Account Deleted?:</span> 
    </strong> 
</h4> 
      @Html.RadioButtonFor(model => model.IsDeleted, true) @Html.Label("Yes") 
      @Html.RadioButtonFor(model => model.IsDeleted, false) @Html.Label("No") 

<br> 
</div> 
<div class="row col-lg-offset-2 top-buffer" id="reason"> 
    <div class="col-sm-2"> 
     <b>Reason for Delete:</b> 
    </div> 
    <div class="col-sm-10"> 
     @Html.TextBoxFor(model => model.reason, new { @class = "form-control", @id = "reason" }) 

     <br /> 
    </div> 
    <div class="row col-sm-12"> 
     <label id="lblErrorMsg" class="has-error" style="color: #BD362F"></label> 
    </div> 
    <div class="col-sm-4"> 
     <button type = "submit" id="Next" name="Next" class="btn btn-primary">Next</button> 
    </div> 
</div> 

腳本:

<script> 
$("#Next").click(function() { 
    if ($("input[name='IsDeleted']" === "True" && $("#reason").val(''))) { 
     $("#lblErrorMsg").text("Please enter meter number"); 
    } else { 
     $("#lblErrorMsg").text(""); 
    } 
}); 

+0

嘗試TRUE;不正確的,也就是你的理由,但實際上建設? – clearshot66

+0

使用條件驗證屬性(請參閱您的[上一個問題]的評論(https://stackoverflow.com/questions/46181191/hide-display-a-input-field-based-on-value-from-htmlradiobuttonfor-and -make-it-ma)) –

+0

@StephenMuecke感謝您的鏈接,這真的很有幫助。但我試圖在視圖中執行此驗證。哪一個更好?這種方法也適用。 –

回答

0

我不能肯定,因爲我沒有看到完整的HTML代碼,但嘗試,而不是:

if ($("input[name='IsDeleted']" === "True" && $("#reason").val(''))) { 

這個:

if ($("input[name='IsDeleted']:checked").val() === "True" && $("#reason").val() == '') 

改善回答了一點,但要確保請將isDeleted單選按鈕值「true」

+0

中應用'[RequiredIf(「IsDeleted」,true,ErrorMessage =「請輸入米數」)]''到'reason'屬性並添加'@ Html.ValidationMessageFor(m => m.reason)'啊萬分感謝!有用。這樣的菜鳥錯誤! –

+0

很高興能幫到你,你能確保我改進的答案也能工作嗎? – pegla

+0

是的,他們都工作! –

相關問題