Trouble with jquery validate when using on checkboxes - jquery-validate

I am trying to use jquery validate to validate the form and I want the user to select atleast 1 checkbox. The reason for having different names is that they match with the database field names.
....
<input class="myclass" type="checkbox" name="option_1">Option 1<br>
<input class="myclass" type="checkbox" name="option_2">Option 2<br>
<input class="myclass" type="checkbox" name="option_3">Option 3<br>
<input class="myclass" type="checkbox" name="option_4">Option 4<br>
<input class="myclass" type="checkbox" name="option_5">Option 5<br>
....
Here is my jQuery code used for validation:
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var valid = $(options[1], element.form).filter(function() {
return $(this).val();
}).length >= options[0];
if(!$(element).data('reval')) {
var fields = $(options[1], element.form);
fields.data('reval', true).valid();
fields.data('reval', false);
}
return valid;
}, jQuery.format("Please fill out at least {0} of these fields."));
$("#formname").validate({
submitHandler: function(form){
console.log("Came here");
return false;
},
rules:{
option_1:{ require_from_group: [1, '.myclass']},
option_2:{ require_from_group: [1, '.myclass']},
option_3:{ require_from_group: [1, '.myclass']},
option_4:{ require_from_group: [1, '.myclass']},
option_5:{ require_from_group: [1, '.myclass']}
}
});
This code is not working. Where am I going wrong ?

Don't see anything wrong inside your .validate() code or in your HTML markup. But I did not check your require_from_group method because you did not need to write this from scratch.
AFAIK, The latest version of the plugin (1.11.1) fixed the bugs in this method. You only have to include the additional-methods.js file and it should work as expected.

Related

Laravel only gets checked items from checklist

I have form with multiple input data and checklists but in controller I'm just getting checked items and no result for unchecked items.
This is what I get
"send_mail" => array:2 [▼
0 => "on"
1 => "on"
]
This is what I need
"send_mail" => array:2 [▼
0 => "off"
1 => "on"
2 => "off"
3 => "on"
]
Blade
<form enctype="multipart/form-data" action="{{route(''xxxxxxxx)}}" method="POST">
#csrf
#method('POST')
<input name="name" id="name" class="form-control">
<div class="form-check">
<input class="form-check-input" checked type="checkbox" name="send_mail[]">
<label class="form-check-label">Send Mail</label>
</div>
<div id="newRows">
// new rows (same as above) will add here by javascript
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
Controller
public function test(Request $request) {
dd($request->all());
}
By default <input type="checkbox"> won't return if it hasn't been checked.
A classic method of fixing this is to duplicate the checkbox with a hidden input:
<input type="hidden" name="send_mail" value="0" />
<input type="checkbox" name="send_mail" value="1" />
This would require, however, moving away from the array of checkboxes you currently have.
The alternative is to use Javascript to submit your form.
I faced a similar scenario back then. I managed to solve it by using JavaScript (jQuery to be specific) to submit the form.
I wrote up a reusable function to append the unchecked items.
Reusable function:
const prepareJQCheckboxFormData = (jQForm, jQSerializedFormData, checkboxNameAttr) => {
let name;
let data = [];
checkboxNameAttr?.substr(-2) === "[]"
? name = checkboxNameAttr
: name = `${checkboxNameAttr}[]`;
let hasItem = false;
jQForm.find("input[name='" + name + "']")
.add(jQForm.find("input[name='" + name?.substr(0, name.length - 2) + "']"))
.each(function () {
if (($(this).attr("checked") === true) || $(this).is(":checked")) {
hasItem = true;
}
});
if (!hasItem) {
jQSerializedFormData.push({
name, value: [""]
});
}
$(jQSerializedFormData).each(function (i, field) {
if (field.name !== name?.substr(0, name.length - 2)) {
data.push(field);
} else {
data.push({
name: `${field.name}[]`,
value: field.value
});
}
});
return data;
};
Form submission:
Assuming that the form 'id' is 'mail-form'
const form = $("#mail-form");
const btnSave = $("#mail-form button[type='submit']");
btnSave.click(function (e) {
e.preventDefault();
$.ajax({
type: form.attr("method"),
url: form.attr("action"),
processData: false, // Important for multipart-formdata submissions!
contentType: false, // Important for multipart-formdata submissions!
cache: false,
data: prepareJQCheckboxFormData(form, form.serializeArray(), "send_mail[]"),
success: function (response) {
// ...
},
error: function (jqXHR) {
// ...
},
beforeSend: function () {
// ...
}
});
});
<div class="form-check">
<input type="checkbox" name="send_mail[]">
<label>Name1</label>
</div>
<div class="form-check">
<input checked type="checkbox" name="send_mail[]">
<label>Name2</label>
</div>
(another 2 div tag here)

Laravel 5 : How to get the value on keyup in edit vue js

In our app, we have validation in code.In Edit part, how do I check if the code already exist? when I tried this
Edit vue
<label>Code</label>
<input type="text" class="form-control" name="edit_code" #keyup="checkCOACode" v-model="coa_code" v-bind:value="chart_of_account_edit.code">
Im encountering this error
conflicts with v-model on the same element because the latter already expands to a value binding internally
EDIT VUE
props: {
chart_of_account_edit: '',
},
checkCOACode(e) {
e.preventDefault();
var code = this.coa_code;
const coa = this.$refs.coaCode
const coaCode = coa.dataset.table
alert(coaCode);
return false;
axios.post("/checkIfCodeExists", {code:code,table:table})
.then((response) => {
var code_checker = '';
if (response.data == 0) {
$('.edit-chart-of-account-finish').removeAttr('disabled','disabled');
// code_checker = 'wala pang ganitong code';
}else{
$('.edit-chart-of-account-finish').attr('disabled','disabled');
code_checker = 'Code is already exist';
}
this.coa_checker_result = code_checker;
});
},
Question: How do I get the input value in my code in Edit Part?
try this.
<input type="text" class="form-control" name="edit_code" #input="checkCOACode" v-model="coa_code" v-bind:value="chart_of_account_edit.code">
EDIT
<label>Code</label>
<input type="text" class="form-control" name="edit_code" #keyup="checkCOACode" v-model="coa_code" v-model:value="chart_of_account_edit.code">
Basing on the error you got, you can't have v-model and v-bind:value in the same element. Try:
<label>Code</label>
<input type="text" class="form-control" name="edit_code" #keyup="checkCOACode" v-model="coa_code">

jQuery validate - group inputs with similar rules

I am using jquery validate, to validate a submitted form. The form has three input fields which have same rule i.e., only number and required - true. Can i write a single rule for all the three inputs say -
rules: {
"depository.startDate":{
required:true,
digits:true
},
"depository.endDate":{
required:true,
digits:true
},
"depository.port":{
required:true,
digits:true
}
},
to
rules: {
"depository.startDate, depository.port, depository.endDate ":{
required:true,
digits:true
}
},
I tried but its not working, any other way i can get this validation work.
--
Thanks
Use the built-in rules() method to add rules. See documentation.
Note: You must call this method after you call .validate(), and it must be combined with an .each().
jsFiddle DEMO
HTML:
<input type="text" name="depository.startDate" />
<input type="text" name="depository.endDate" />
<input type="text" name="depository.port" />
jQuery:
$('#form').validate({
// your other options
});
// the following method must come AFTER .validate()
$("input[name*='depository']").each(function() {
$(this).rules('add', {
required: true,
digits: true
});
});
This method can also be very useful when you are dynamically adding fields to your form.
The following to combine with custom messages:. Note that the format is slightly different than when adding rules as options within .validate()...
$("input[name*='depository']").each(function() {
$(this).rules('add', {
required: true,
digits: true,
messages: {
required: "Required input",
digits: "Only digits please"
}
});
});
Alternatively, you can use a class instead, but for it to work properly, you must also combine it with an .each()...
jsFiddle DEMO
HTML:
<input type="text" class="myclass" name="depository.startDate" />
<input type="text" class="myclass" name="depository.endDate" />
<input type="text" class="myclass" name="depository.port" />
jQuery:
$('form').validate({
// your other options
});
// the following method must come AFTER .validate()
$('form').find('.myclass').each(function() {
$(this).rules('add', {
required: true,
digits: true
});
});

Using Validation Plugin, how can i submit form when either one of the checkbox is checked or specific text field is not empty

//Using Validation Plugin, how can i submit form when either one of the checkbox is checked or specific text field is not empty? I have checkboxes which generates dynamically and category_name text field. I want to submit form when either one of the checkbox is checked or category_name text field is not empty...
<?php
while($cat_row = "fetch_result"){
$tr.='<b><input type="checkbox" class="required" name="category[]" value="'.$cat_row['category_name'].'" id="category[]" checked/>'.$cat_row['category_name'].'</b>';
}
?>
//HTML File
<body>
<form id="abc" name="abc" action="PATH_TO_PHPFILE" method="post" enctype="multipart/form-data" >
<div id="cd">
<?=$tr?>
<div id="err"></div>
</div>
<input type="text" name="category_name" id="category_name" class="text_box" value="" />
</form>
<script>
$(function() {
$("form").validate({
rules:{
category:{
required:true,
minlength:2
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
},
submitHandler: function(form){
var options = {
success:function (data){
$.unblockUI();
//do something
},
beforeSubmit:function (){
//do something
}
};
$(form).ajaxSubmit(options);
}
});
});
</script>
</body>

jquery.validation required not stopping postback

I am using jQuery validation to attempt to keep a user from posting back unless he meets a couple of qualifications. But the required option doesn't seem to be keeping the form from submitting...
Here is jsFiddle with an example: jsFiddle
I double checked my jQuery code and it would seem as though it was working. jsFiddle says it valid code. So I am not sure what the hangup is?
Thanks
jQuery.validate uses names for the rules, not ids. So replace the ids with names in your input fields.
Also your form should be <form id="temp1"> and not <form id="#temp">.
Here's a link to your fixed code:
<form id="temp1">
<input type="text" name="HospitalFinNumber"/> Hospital Fin<br/>
<input type="text" name="DateOfBirth"/>Date of Birth<br/>
<input type="text" name="AdmitDate"/>Admit Date<br/>
<input type="text" name="Comment"/>Comment<br/>
<input type="submit" value="Save" class="button" id="btClick"/>
</form>
and the script:
$(document).ready(function () {
$("#temp1").validate({
rules: {
HospitalFinNumber: {
required: true,
minlength: 6
},
DateOfBirth: {
required: true
},
AdmitDate: {
required: true
},
Comment: {
required: function (element) {
return $(element).val().length < 4000;
},
maxlength: 4000
}
},
messages: {
HospitalFinNumber: 'Please Enter a Hospital Fin number',
DateOfBirth: 'Please enter a valid Date Of Birth',
AdmitDate: 'Please select an Admit Date',
Comment: 'Why dont you stop attempting to put in more than 4000 characters? Thanks...'
}
});
});

Resources