我的问题与jquery验证有关。我有一个表单,并且验证正在输入字段上工作,但是我对如何在单选按钮上使用验证感到困惑,因为我有三个单选按钮,用户只能选择一个。所有单选按钮都有其受尊重的字段。我必须对此进行验证。
示例:我选择第一个收音机,然后用户也应输入book1和book2字段。如果您选择第二个收音机,则用户应输入fruit1和fruit2字段值。
如果用户仅选择单选按钮而不填写字段详细信息,然后单击“提交”,则将显示验证。
我尝试了一些代码。它适用于第一个单选按钮,但是如果有用户选择第二个单选按钮怎么办?
这是我得到的输出。
单选按钮如果字段为空,则通过Jquery验证检查Book
请注意,我在这里选择了水果,然后单击了提交按钮,但验证未显示
原因是我没有得到,因为我仅添加了书单选按钮验证。现在如何用于水果和主题?
book1: {required: true},
book2: {required: true}
$(document).ready(function() {
$("input[name='books_fruit_sub']").click(function() {
var test = $(this).val();
$(".show_fields").hide();
$("#show" + test).show();
});
$('#form').validate({ // initialize the plugin
rules: {
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
book1: {
required: true
},
book2: {
required: true
}
},
submitHandler: function(form) { // for demo
form.submit();
}
});
});
ul {
text-decoration: none;
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
}
.error {
color: red;
}
<form action="" id="form">
<input type="text" name="mobile" placeholder="Mobile">
<ul>
<li>
<input type="radio" name="books_fruit_sub" id="books" value="books" checked>
<label for="books">Books</label>
</li>
<li>
<input type="radio" name="books_fruit_sub" id="fruit" value="fruit">
<label for="fruit">Fruit </label>
</li>
<li>
<input type="radio" name="books_fruit_sub" id="subject" value="subject">
<label for="subject">Subject </label>
</li>
</ul>
<div>
<div class="show_fields" id="showbooks">
<input type="text" name="book1" placeholder="Book 1">
<input type="text" name="book2" placeholder="Book 2">
</div>
<div class="show_fields" id="showfruit" style="display: none;">
<input type="text" name="fruit1" placeholder="Fruit 1">
<input type="text" name="fruit2" placeholder="Fruit 2">
</div>
<div class="show_fields" id="showsubject" style="display: none;">
<input type="text" name="subject1" placeholder="Subject 1">
<input type="text" name="subject2" placeholder="Subject 2">
</div>
</div>
<input type="submit" name="send" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
答案 0 :(得分:0)
您不需要jQuery。使用ES20xx,数据属性和CSS,可以轻松创建自己的表单验证。为了好玩,让我们根据您的代码制作一个示例。
checkRadio
; switchFieldsBasedOnRadioChoice
。该功能由clickHandling
激活。我们使用checkRadio
中的选定值来识别div#show[chosen value]]
,以便能够显示包含属于选定值的输入元素的右div; data-check
表示为html并由[data-check]
的值激活的字段,该字段称为fieldChecks
; [data-check]
表示的所有字段的字段值有效性,并警告该字段值是否无效,即checkValues
,由{激活{1}}; clickHandling
处理程序,该处理程序从先前的输入值中删除警告,以检查用户是否单击或聚焦于表单字段之一; focusin
中。我们对(输入字段容器)-div
使用css类.invalid
来对包含输入字段的警告设置样式(如果适用)。div
,click
)使用event delegation。
focusin
// check value of a radio button
const checkRadio = name => {
const isChecked =
Array.from(document.querySelectorAll(`[name='${name}']`))
.filter(rb => rb.checked);
return isChecked.length ? isChecked[0].value : null;
};
// validity checks for field values ([data-check])
const fieldChecks = {
mobile: value => {
const valueClean = value.replace(/[^\d]/g, "");
return {
cando: valueClean.length === 10,
instruction: "Invalid: need 10 digits, you can use spaces and '-'"
};
},
booksOrFruits: value => ({
cando: value.trim().length >= 5,
instruction: "Invalid: all fields ≥ 5 characters"
}),
};
// add event listeners
document.addEventListener("click", clickHandling);
document.addEventListener("focusin", removeWarnings);
// click handling delegate
function clickHandling(evt) {
const origin = evt.target;
if (origin.type === "radio") {
return switchFieldsBasedOnRadioChoice(origin);
} else if (origin.id === "validate") {
return checkValues();
}
}
// focusin handling delegate: remove warnings on focus
function removeWarnings() {
console.clear();
Array.from(document.querySelectorAll(".notvalid"))
.forEach( el => el.classList.remove("notvalid") );
}
// check all field values and warn for invalid values in required fields
function checkValues() {
console.clear();
const checks = Array.from(document.querySelectorAll("[data-check]"));
let cando = true;
checks.forEach( input => {
// check for existence of input.dataset.check
if (!fieldChecks[input.dataset.check]) {
throw new Error(
`You forgot to add '${input.dataset.check}' to fieldChecks!`
);
}
const parent = input.parentNode;
// don't check input values from parent class "show_fields hidden"
if (parent.classList.contains("show_fields")
&& parent.classList.contains("hidden")) {
return false;
}
// perform the check denoted by [data-check] from the input field
const fieldChck = fieldChecks[input.dataset.check](input.value);
// if invalid value, use css/data-attributes to style a warning
if (!fieldChck.cando) {
parent.classList.add("notvalid");
if (fieldChck && fieldChck.instruction) {
parent.dataset.instruction = fieldChck.instruction;
}
cando = false;
} else {
parent.classList.add("valid")
}
} );
// all fields checked out ok
if (cando) { console.log("you're ok"); }
}
// show input fields belonging to a chosen radio input field
function switchFieldsBasedOnRadioChoice(origin) {
Array.from(document.querySelectorAll(".show_fields"))
.forEach(v => v.classList.add("hidden"))
const chosenValue = checkRadio(origin.name);
document.querySelector(`#show${chosenValue}`)
.classList.remove("hidden");
}
body {
margin: 2em;
font: normal 12px/15px verdana, arial, sans-serif;
}
input[type=text] {
margin: 0.3em 0.3em 0 0;
padding: 2px 4px;
}
button {
margin-top: 0.3em;
}
/* fields originating from radio choice */
.show_fields {
display: table-row;
visibility: "visible";
opacity: 1;
transition: opacity ease-in 0.5s 0s;
}
.hidden {
opacity: 0;
transition: opacity ease-out 0.1s 0s;
visibility: collapse;
}
/* styling related to validation */
.notvalid input {
border: 1px solid red;
}
.notvalid[data-instruction]:after {
content: attr(data-instruction);
margin-left: 0.2em;
}
.notvalid ::placeholder {
color: red;
}
.valid:after {
font-weight: bold;
content: "\2714";
color: green;
}
.valid input {
color: green;
}
答案 1 :(得分:0)
仅使用返回true或false的函数,具体取决于是否选择了相关的无线电按钮。
book1: {
required: function() {
return $('#books').is(':checked');
}
},
book2: {
required: function() {
return $('#books').is(':checked');
}
},
fruit1: {
required: function() {
return $('#fruit').is(':checked');
}
},
fruit2: {
required: function() {
return $('#fruit').is(':checked');
}
},
..
因此,请像使用"fruits"
一样使用复数形式"subjects"
和"books"
作为单选按钮。
Here是您在plunker中修改并工作的代码。
答案 2 :(得分:-1)
从验证程序初始化中删除book1和book2的规则,然后在您的点击处理程序中添加此
$(".show_fields").find("input").removeAttr("required");
$("#show" + test).find("input").attr("required" , "required");
也在html中将required属性添加到输入book1和book2