Skip to content

Instantly share code, notes, and snippets.

Created March 18, 2018 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/e46dc90f23c8216086062b2f0fe02091 to your computer and use it in GitHub Desktop.
Save anonymous/e46dc90f23c8216086062b2f0fe02091 to your computer and use it in GitHub Desktop.
.required:after {
content: "*";
color: red;
}
<form id="myform">
<label for="input1">Input 1</label>
<input type="text" name="input1" id="input1">
<br>
<label for="input2">Input 2</label>
<input type="text" name="input2" id="input2" required>
<br>
<label for="input3">Input 3</label>
<input type="text" name="input3" id="input3" data-rule-required="#checkbox:checked">
<br>
<label for="input4">Input 4</label>
<input type="text" name="input4" id="input4">
<br>
<label for="input5">Input 5</label>
<input type="text" name="input5" id="input5">
<br>
<label for="checkbox">
<input type="checkbox" id="checkbox"> Make input 3 required
</label>
<br><br>
<button id="mybtn" type="button">Mark required fields</button>
</form>
<pre>
- Check the checkbox to lake the third input required
- Fill the first input to make the fourth one required
- Fill the second input to make the fifth one required
</pre>
var $form = $("#myform");
$form.validate({
rules: {
input1: {
required: true
},
input4: {
required: {
depends: function(element) {
return $("[name='input1']").val() !== "";
}
}
},
input5: {
required: function(element) {
return $("[name='input2']").val() !== "";
}
}
}
});
$("#mybtn").on("click", function() {
markAsRequired($form.find("input[type='text']"));
});
function shouldMarkAsRequired(element) {
var rules = $(element).rules();
var requiredParam = rules.required;
if (typeof requiredParam === "string") {
return !!$(requiredParam, element.form).length;
}
if (typeof requiredParam === "function") {
return requiredParam(element);
}
return requiredParam === true;
}
function markAsRequired(fields) {
var field;
var $label;
for (var i = 0; i < fields.length; i++) {
field = fields[i];
$label = $("label[for=" + fields[i].id + "]");
if (shouldMarkAsRequired(field)) {
$label.addClass("required");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment