簡體   English   中英

表單驗證規則動態變化

[英]Form validation rules changing dynamically

 var mandatory = { emailAddressTextBox: { required: true, email: true }, passwordTextBox: { required: true, minlength: 6, maxlength: 24, } }; var nonmandatory = { nameTextBox: { required: true, maxlength: 50 }, loginEmailAddressTextBox: { required: true, email: true }, loginPasswordTextBox: { required: true, minlength: 6, maxlength: 24, }, loginPasswordAgainTextBox: { required: true, minlength: 6, maxlength: 24, equalTo: "#loginPasswordTextBox" } }; $("#myForm").validate({ rules: ($("input[name='country']").val() === "US") ? mandatory : nonmandatory; });

我想根據國家/地區名稱動態更改 ajax 中的表單驗證規則。

假設它是英國

只有電子郵件和密碼應該是強制性的。

或者如果是美國

與電子郵件一起,名字和姓氏應該是強制性的。

我是 Ajax 的新手。

誰能幫我?

提前致謝!

試試這個答案...在驗證規則而不是required:true你必須使用這個函數

required: function(element) {
                if ($("#country option:selected").val()== '1') {
                    return false;
                }   
                else {
                    return true;
                }
         }

 $(document).ready(function () { $("#form").validate({ rules: { "name": { required: function(element) { if ($("#country option:selected").val()== '1') { return false; } else { return true; } }, minlength: 5 }, "email": { required: function(element) { if ($("#country option:selected").val()== '1') { return true; } else { return true; } }, email: true }, "password": { required: function(element) { if ($("#country option:selected").val()== '1') { return true; } else { return true; } }, email: true } }, messages: { "name": { required: "Please, enter a name" }, "email": { required: "Please, enter an email", email: "Email is invalid" }, "password": { required: "Please, enter password" } }, submitHandler: function (form) { // for demo alert('valid form submitted'); // for demo return false; // for demo } }); });
 body { padding: 20px; } label { display: block; } input.error { border: 1px solid red; } label.error { font-weight: normal; color: red; } button { display: block; margin-top: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script> <form id="form" method="post" action="#"> <select id="country"> <option value="1">US</option> <option value="2">UK</option> </select> <label for="name">Name</label> <input type="text" name="name" id="name" /> <label for="email">Email</label> <input type="email" name="email" id="email" /> <label for="name">Password</label> <input type="text" name="password" id="password" /> <button type="submit">Submit</button> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM