The form
<form id="form_reg" name="form_reg" method="post" action="">
<input type="radio" id="y" name="opt" value="y"><label for="y"><span>YES</span></label>
<input type="radio" id="n" name="opt" value="n"><label for="n"><span>NO</span></label>
<button id="reg_submit" value=" " type="submit"></button>
</form>
JS Validation
$().ready(function() {
$("#form_reg").validate({
rules: {
opt:{
required: true
}
},
messages: {
opt: {
required: "Select one "
}
}
});
$("#form_reg").validate();
})
This works good until I add CSS
input[type="radio"] {
display:none;
}
input[type="radio"] + label span {
width:27px;
height:25px;
background:url(/images/radio.svgz) no-repeat;
cursor:pointer;
}
input[type="radio"]:checked + label span {
width:27px;
height:25px;
background:url(/images/radio_a.svgz) no-repeat;
cursor:pointer;
}
I guess this is because the default radio buttons are hidden.
How can I validate this form with these custom radio inputs?
To perform a validation on hidden fields you need to override the default 'ignore' setting with an empty array
$(function() {
$("#form_reg").validate({
ignore:[],
rules: {
opt:{
required: true
}
},
messages: {
opt: {
required: "Select one "
}
}
});
});
Presumably you have a good reason to want to require a radio button that the user can't see. For instance when validating a form that is spread across several jquery ui tabs for instance, some fields may be hidden when the form is submitted.
Don't call validate twice on document ready also - although it does no harm there is no point the second call won't do much.
Related
i am creating a form for searching a client, using either id or email both are set to be unique. Application made on Codeignitor.
I have created a form with two radio buttons, one for search with ID and another for search with mail+dob.
Depending on the radio button selected, corresponding input fields shown.
In controller, it choose the model function based on the radio button value.
This is I coded, i need to pass the value of radio button to Controller.php file
Form(only included the radio button)
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="mail">Using DOB</label>
</div>
I expected to get the radio button value correctlyenter image description here
JS:
$('input[name="optradio"]').click(function(){
var optradio = $(this).val();
//or
var optradio = $("input[name='optradio']:checked").val();
if(optradio == 'id'){
//do your hide/show stuff
}else{
//do your hide/show stuff
}
});
//on search button press call this function
function passToController(){
var optradio = $("input[name='optradio']:checked").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({optradio : optradio}),
success: function (data) {
}
});
}
Try this
<script type="text/javascript">
$( document ).ready(function() {
$("#usingdob, #usingmail").hide();
$('input[name="radio"]').click(function() {
if($(this).val() == "id") {
$("#usingId").show();
$("#usingdob, #usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob, #usingmail").show();
}
});
});
</script>
One thing I noticed is that you have 'mail' as a value in the DOB option. Another is that there seems to be 3 options and yet you only have 2 radios?
I adjusted the mail value to dob and created dummy divs to test the code. It seems to work.
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
console.log($(this).val());
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="dob">Using DOB</label>
</div>
<div id="usingId">
Using Id div
</div>
<div id="usingdob">
Using dob div
</div>
<div id="usingmail">
Using mail div
</div>
As far as passing the value to the controller goes, ideally the inputs should be in a form. When you submit the form, the selected value can be passed to the php.
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['optradio']))
{
Radio selection is :".$_POST['optradio']; // Radio selection
}
?>
If you want to get currently checked radio button value Try below line which will return current radio button value
var radioValue = $("input[name='gender']:checked").val();
if(radioValue)
{
alert("Your are a - " + radioValue);
}
I have a simple view-model with a few required attributes... I want each input to highlight red if the corresponding property is not valid, but I don't want this highlighting to display when the page is initially loaded... only when a value changes or when the user tries to save / continue...
Right now it's validating the view-model on initial load because I'm specifying data-bind="css: { error: name.isValid() == false }", but I don't know of any other way to get this to work dynamically (similar to how jQuery unobtrusive validation works)...
var foo = { name: ko.observable().extend({required: true}) };
<div data-bind="css: { error: !name.isValid() }">
<input type="text" data-bind="value: name" />
</div>
Any ideas on how to make this work would be appreciated... Thanks!
A better approach is to configure knockout validation to decorate the element with the validationElement class. This is done by adding this configuration option:
ko.validation.configure({ decorateElement: true });
Click here to see a jsfiddle demonstrating this.
****EDIT, IN RESPONSE TO COMMENT FROM QUESTION ASKER***
If you need to decorate the parent element, a more elegant and reusable solution is to apply this custom binding to the parent element.
Javascript
ko.bindingHandlers.parentvalElement = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var valueIsValid = valueAccessor().isValid();
if(!valueIsValid && viewModel.isAnyMessageShown()) {
$(element).addClass("parentError");
}
else {
$(element).removeClass("parentError");
}
}
};
And apply the binding in your HTML like so:
<form data-bind='submit:OnSubmit'>
<label data-bind='parentvalElement:name'>
<span>Name</span>
<input data-bind="value: name" />
</label>
<input type='submit' value='submit' />
<form>
Take a look at this updated jsfiddle to see it in action.
So, here is the solution I came up with:
var Foo = function()
{
this.name = ko.observable().extend({required: true}).isModified(false);
this.validate: function()
{
if (!this.isValid())
{
//... loop through all validated properties and set .isModified(true)
return false;
}
return true;
};
ko.validation.group(foo);
};
var Bar = function()
{
this.foo = new Foo();
this.errors = ko.observableArray([]); //<-- displays errors for entire page
this.save = function()
{
if (!this.foo.validate())
{
this.errors(ko.toJS(this.foo.errors()));
}
};
}
ko.applyBindings(new Bar());
And here is the markup...
<div data-bind="with: foo">
<div class="control-group"
data-bind="css: { error: name.isModified() && !name.isValid() }">
<label class="control-label">Name<span class="help-inline">*</span></label>
<div class="controls">
<input type="text" class="input-block-level" placeholder="Name"
data-bind="value: name, event: { blur: function () { name.isModified(true); }}" />
</div>
</div>
<div class="alert alert-error"
data-bind="visible: $parent.errors().length > 0">
<h5>Errors!</h5>
<ul data-bind="foreach: $parent.errors()">
<li data-bind="text: $data"></li>
</ul>
</div>
</div>
<button type="submit" class="btn btn-primary" data-bind="click: save">Save</button>
and here is the CSS
.error { color: Red; font-weight: bold; }
.help-inline { display: none; }
.error .help-inline { display: inline-block; }
.error input { border-color: Red; }
I have the following code and it works fine, EXCEPT when you clear the property after you have inserted an item. The error shows up right away.
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error'
});
FirstName: ko.observable().extend({
required: true
}),
and I have add method in the knockout viewmodel
addItem: function () {
if (!viewModel.isValid()) {
viewModel.errors.showAllMessages();
return false;
} else {
//DO SOMETHING
this.SomeCollection.push(newInterviewee);
this.FirstName(null);
}
},
I have the following in the HTML:
<div>
<label>First Name</label>
<input data-bind="value: FirstName, validationElement: FirstName, valueUpdate: 'keyup'" class="input" type="text">
</div>
<div>
<div>
<input data-bind="click: addItem" class="button" type="button">
</div>
The problem is that after I call this.FirstName(null). The error shows up right away! I want the error to show up only when they press the button even after the property is cleared
Here is the solution that is provided by Steve Greatrex: https://github.com/Knockout-Contrib/Knockout-Validation/issues/210
We had the same issue on our project. We solved this by forcing isValid to true.
addItem: function () {
if (!viewModel.isValid()) {
viewModel.errors.showAllMessages();
return false;
} else {
//DO SOMETHING
this.SomeCollection.push(newInterviewee);
this.FirstName(null);
viewModel.isValid(true);
}
},
To be able to do this, you need to overwrite ko.validation's definition for the isValid computed as follows:
observable.isValid = ko.computed({
read: function() {
return observable.__valid__();
},
write: observable.__valid__
}
);
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? 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>