genvalidator: check for checkbox in form validation - javascript

I'm using genvalidator to have some tests on input fields in a form. Problem is I can't find a way to test if a checkbox has been checked. This is how all the fields are set:
frmvalidator.addValidation("name","req","Insert your name");
frmvalidator.addValidation("city","req","Insert your city");
frmvalidator.addValidation("phone","req","Insert your phone number");
This is my checkbox
<input type="checkbox" name="agree" id="agree "value="yes"/>
How can I make it mandatory with genvalidator?
This is the part that handles the form process (in short: if there aren't errors, it's ok):
if(empty($name)||empty($city)||empty($phone)||BLAHBLAH)
{
$errors .= "\n Mandatory field. ";
}
if(empty($errors))
{
// send the email
}
It tried with this JS code with no luck:
function validate(form) {
if(!document.form1.agree.checked){alert("Please check the terms and conditions");
return false; }
return true;
}
If possible I'd like to use genvalidator functions. :)

You are expending a lot of energy trying to make the javascript plugin work.
Would you consider working with jQuery? If you haven't yet kicked its tires, it's a lot easier than it sounds -- and much more uniform / faster to type than plain js.
To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Then, you can easily create you own verification routines, with FULL control over what you are doing.
Here is a working example for you to study. As you can see, the code is pretty minimal.
When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. If any field fails validation, we can return control to the user with the field colored and in focus.
If all fields pass validation, then we issue the submit() method on the form ID, and off it goes (to the location specified in the action="somepage.php" attribute).
Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. This code runs every time a field is exited, regardless whether the field has validation coloring or not. This is not very efficient (although it certainly won't hurt anything) and is only intended to demonstrate what is possible.
Hmmmmm. I think it would be more efficient to have a class with certain attributes, and add/remove that class if fail validation. Okay, I liked that idea enough that I created a new jsFiddle using that method to demonstrate what that would look like.
jsFiddle here
HTML:
<form id="fredform">
First Name: <input id="fname" name="fname" type="text"/>
Last Name: <input id="fname" name="fname" type="text"/>
Email: <input id="fname" name="fname" type="text"/>
<input id="mysub" type="button" value="Submit" />
</form>
jQuery:
arrValidate = ['fname','lname','email']
$('#mysub').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed the [' +nextFld+ '] field.');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#fredform').submit();
});
//Remove any css validation coloring
$('input:not([type=button])').blur(function(){
$(this).css({'border':'1px solid lightgrey','background':'white'});
});
Note that there is also a jQuery validation plugin that looks very professional. I haven't played with it myself, always preferring to code my own stuff, but here is the link:
http://jqueryvalidation.org/documentation/
Note the very cool demo
Just so you know what to expect: implementing this plugin would be more difficult than the methodology I suggested above.
` ANSWER TO YOUR COMMENT QUESTION: `
Regarding your comment and the code posted at pastebin:
(Sorry for the long answer, but I want it to be clear. Please read carefully.)
(1) Please wrap your javascript code in a document.ready function. This is my fault; I should have added it to my code example. Otherwise, the code will execute before the DOM fully exists and event triggers will not be bound to the controls (because they do not yet exist in the DOM). Therefore:
arrValidate = ['checkbox']; //a global variable
$(document).ready(function() {
$('#submit').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed [' +nextFld+ ']');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#contact_form').submit();
}); //END #submit.click
}); //END document.ready
(2) Your checkbox still has the value="yes" attribute that breaks the javascript. Please change this:
<input type="checkbox" name="checkbox" id="checkbox" value="yes" /> <small>Ho
to this:
<input type="checkbox" name="checkbox" id="checkbox" /> <small>Ho
(3) There is no need to have type="submit" for your <input value="Invia"> button, nor is there a need for a name= attribute on that control.
First the name= attribute: it is only useful when passing data from that control to the PHP(?) file that processes your form: ($_SERVER['SCRIPT_NAME']). The name= part is the variable name, and the value of the control is the variable value. The button has no data to pass along, so does not need to have a variable name assigned to it.
Next, the type="submit": This is not required, because you can use jQuery to submit the form any time you want. In the old days, before javascript/jQuery, we had forms. Back in those days, the only way to make the form submit was to use the type="submit" attribute. There was no such command as: $('#myFormId').submit(); -- but today there is. So change that attribute to type="button" and let jQuery submit the form for you. Trust me, this works!
Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. You cannot simply return control to the user when there is an error, because the form has been told to submit. (You must use event.preventDefault() to override the default behaviour -- you can read about that later.)
(4) Checkbox values must be checked using one of these methods. Checkboxes do not have a value. This is my fault again, I should have written a checkbox into my example.
$('#submit').click(function() {
var nextFld, i ;
//Validate the checkbox:
if ( $('#checkbox').is(':checked') == false ) {
alert('You must read the informativa and check the checkbox at bottom of form');
return false;
}
//Validate the rest of the fields
for (i=0; i<arrValidate.length; i++){
(5) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute.
This is a weird thing, but you need to know it. I just learned it (again) while troubleshooting my jsFiddle example.
If you want to use jQuery to submit your form (and we do) via the .submit() method, then no element in your form can have the name= or id= attribute set to "submit". The INPUT button had both name= and id= set to submit; that is why it wasn't working.
Reference: http://blog.sourcecoder.net/2009/10/jquery-submit-on-form-element-does-not-work/
See the revised code example in the jsFiddle:
Revised jsFiddle here
Please Please Please study the above jsFiddle. You should be able to dump the genvalidator plugin entirely. If you understand the jsFiddle completely, you will be in a new place as a programmer.

If you're using jQuery, try checking this way:
function validate(form) {
if(!$('[name="agree"]').prop('checked')){
alert("Please check the terms and conditions");
return false;
}
return true;
}
or try using
function validate(form) {
if(!$('[name="agree"]')[0].checked){
alert("Please check the terms and conditions");
return false;
}
return true;
}

This is untested but I think it would look something like this:
function DoCustomValidation() {
var frm = document.forms["myform"];
if(document.form1.agree.checked != true) {
sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
return false;
}else{
return true;
}
}
Note that you must customize this line to have the correct name of your own form:
var frm = document.forms["myform"];
Plus, you also need to associate the validation function with the validator object:
frmvalidator.setAddnlValidationFunction("DoCustomValidation");
Source: genvalidator documentation

Since you've tagged the question with JQuery, this should work for you:
function validate(form) {
if ($("#agree :checked").length < 1) {
alert("Please check the terms and conditions");
return false;
}
return true;
}
I tend to use this approach because it also works for multiple checkboxes or radio button groups as well. Note, however, that it does not care about what was checked, just that something was checked . . . in the case of a single checkbox, this acts as a "required to be checked" validation as well.

Add a new div for error location above your input tag like this :
<div name="formname_inputname_errorloc" class="errorstring">
//<your input tag goes here>
Make sure u have the css for errorstring class in your css file. and the other req js files
Try to search the demo for gen validator it has been totally explained in the demo

frmvalidator.addValidation("agree","selmin=1","Please select checkbox");

Related

How to display "Please fill out this field" for all empty and required fields in html form?

I have a form as shown in the fiddle https://jsfiddle.net/vrn7zx5h/3/ in which I want to show the warning sign "Please fill out this field" at the same time for all unfilled required fields.
I found the answer on SO (as shown below) but i am not sure how to integrate with the fiddle.
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
Problem Statement:
I am wondering what changes I should make in the fiddle so that the above pasted SO answer works with the fiddle.
Here is a JS fiddle that will show all error at one time. It is just barebone and not fancy. You'll need to make it fancy on your own. I also disabled the built-in validator as well with novalidate in the form tag.
https://jsfiddle.net/6kxc9hmq/1/
FYI: I also did not put in the functionality to hide the error message on next run, if the input now satisfies the condition.
Basically, I attached a submit event handler to the form and if the validator returned false, I told the form to not submit. Works only on IE9+ (I think) all the other browsers are usually fine with this method. The validator is basically just checking if the value of the input met the condition that I specified.
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
I think it should look like this, if I understand what you mean
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
In your form, add empty divs after each input element. And you can conditionally display messages in the div in your validation. E.g if(name ==‘ ‘){div.innerHTML = ‘please enter your name’}
The required Attribute
Add the required attribute to your form.
The required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted.

Checkbox element disappears from serialize() when not checked

I have a form/input checkbox like so:
<form id="the_form">
<input name="my_checkbox" type="checkbox" value='true' />
</form>
When I run a $("#the_form").serialize(); my_checkbox only comes up as true when it is checked. If it is not checked, there is no data that comes with my_checkbox.
Is there a way I can make it so if the data is not checked, it'll at least give a null value to my_checkbox or something?
This is normal behavior for HTTP form posts from web browsers: checkbox values are not presented when not checked, since you can infer their value from their absence.
Frankly, this is can be solved with plain engineering: the code that presents the form knows if the checkbox should be present, so the code that receives the post should also know that the checkbox should be present and can implicitly determine the correct, non-checked, value of the checkbox.
If you will give me an indication of your back end technologies I may be able to provide some ideas for how you might engineer the presence of a value for non-checked checkboxes in your form data collection.
If you truly must have the value posted, which I consider less than ideal, then you can add a hidden input that mirrors the value of your checkbox and which is updated by JavaScript:
<form id="the_form">
<input id="my_checkbox_ui" name="my_checkbox_ui" type="checkbox" value='true' />
<input id="my_checkbox" name="my_checkbox" type="hidden" value='true' />
</form>
<script>
$(document).ready(function () {
$('#my_checkbox_ui').change(function () {
$('#my_checkbox').val($(this).val());
});
});
</script>
Keep in mind that doing this when not absolutely needed creates extra complexity and yields a poorer system:
The form post will be larger, using more bandwidth
The simple correspondence between visible elements and underlying posted elements is broken, a possible source of confusion and mistakes for future developers working with this code.
The need for JavaScript creates additional surface area of possible breakage--there are more moving parts that can break and this causes fragility.
Related to the two previous points, if someone copies the form and tries to use it in other code, it won't work correctly, even though the UI looks like it is working.
Another way that you could possibly solve this is to semi-unobtrusively injection the the checkbox-shadowing elements with javascript:
<form id="the_form">
<input id="my_checkbox_ui" name="my_checkbox_ui" type="checkbox" value='true' />
<input id="my_checkbox" name="my_checkbox" type="hidden" value='true' />
</form>
<script>
function getShadowFn(id, shadowId) {
return function() {
$('#' + shadowId).val($('#' + id).val());
};
}
function convertCheckboxesToAlwaysPostingCheckboxes() {
$('input[type="checkbox"]').each(function(id, el) {
var $el = $(el);
var name = $el.prop('name');
var id = $el.prop('id');
var shadowId = id + '_shadow'
$el.prop('name', name + '_ui');
$('<input type="hidden" id="' + shadowId + '" name="' + name + '">')
.insertAfter($el);
$el.change(getShadowFn(id, shadowId));
});
}
$(document).ready(convertCheckboxesToAlwaysPostingCheckboxes);
</script>
This is still added complexity, but it is less fragile because it is no longer specific to any checkbox, and all the checkboxes will now work correctly with just this one bit of code (though I didn't test it at all, so please take it as inspiration rather than prescription). So you can get this code working right, and then use it over and over.
I submit my checkbox through javascript, and since I parse a lot of information in the backend, and my script looks for these variables, it didn't seem like an appropriate solution to do this after the form was submitted.
Thanks to everyone that gave me guidance, but I figured out a way to solve this without too much heavy lifting.
function submitForm()
{
//serialize all the inputs in the form
var data_serialize = $("#the_form").serialize();
//check to see if any checkbox's are not checked, and if so, make them false
$("#the_form input:checkbox:not(:checked)").each(function(e){
data_serialize += "&"+this.name+'=false';
});
//submit the form
var url = "/submit";
$.ajax({ type: "POST", url: url, data: data_serialize,
success: function(data) { },
error: function(data) { }
});
return false;
}

Form onsubmit() does not function

I want to control my form for the required input texts, and I have made a function in javascript. But when I click the button, and I havent fill the required field nothing the message do not appear, and I can go to the other page.
the function is:
function Validate(){
// create array containing textbox elements
var inputs = [document.getElementById('firstname1')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
and the part of form is:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#">
<input type="submit" value="Proceed" id="submit1" onclick="displayform2()" class="button" style=" margin-top: -40px;margin-left: 60%;width: 25%" disabled>
I have noticethat if I put off the onclick method in the button it works, but I should have this method at the button...How can I solve this?Please help me
function displayform2() {
/*For desktop*/
if (document.getElementById('desktop1').style.display=='block') {
document.getElementById('desktop1').style.display='none';
document.getElementById('desktop2').style.display='block';
document.getElementById('desktop3').style.display='none';
}
/*For mobile*/
if (document.getElementById('mobile1').style.display=='block') {
document.getElementById('mobile1').style.display='none';
document.getElementById('mobile2').style.display='block';
document.getElementById('mobile3').style.display='none';
}}
It opens another form in the page...so when I click the button the first form dissapeared and the second form is displayed
You have this: var inputs = [document.getElementById('firstname1')];
Then you try to loop through that. I'm betting firstname1 is a field, so it's either null (if that field doesn't exist) or an array with only one element (the field). It looks like you are trying to check all required fields, so that won't work.
I'm not 100% what you ultimately want to do, but it will likely be much easier if you use a framework like jQuery; otherwise, you are going to have to do some complicated case-handling for different browsers.
Nowhere in your code do you call submit. That is why the function in the onsubmit handler is not triggered. If you want the button to submit the form, it would need to be a submit button.
Your example is a little unclear. For example, you are trying to validate whether a value has been entered into the input "firstname1", but you don't have markup for that element in your HTML.
I suspect what you are trying to do is to validate whether the form has been filled out or not. Something like the following (which validates input "firstname1") will do the job:
$(document).on("click", "#submit1", function(){
if($("#firstname1").val() == "" || $("#firstname1").val() == null){
alert("Please complete all fields.");
}
});
Working example here
The above requires jQuery, but can also be converted into vanilla JavaScript.
Load the jQuery library in the "head" section of your document by including the following code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

how to check if input field is empty on submit [duplicate]

This question already has answers here:
Check if inputs are empty using jQuery
(22 answers)
Closed 9 years ago.
I'm using jQuery so i wonder how can i show error message after i click submit button only if an input field is empty.
Below the code my simple form how to apply to it.
<form id="myid" name="myid" method="post" action="hook.php">
name : <input type="text" name="name" id="name">
age : <input type="text" name="age" id="age">
<input type="submit" id="submit" name="submit" value="Save" />
</form>
I would like to show error like this
As someone has already mentioned, you should probably look to use an external library for validation. That said, this seems like it might work (see JSFiddle):
var $form = $("#myid"),
$errorMsg = $("<span class='error'>This field is required..!!</span>");
$("#submit").on("click", function () {
// If any field is blank, we don't submit the form
var toReturn = true;
$("input", $form).each(function () {
// If our field is blank
if ($(this).val() == "") {
// Add an error message
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
// If the field is not blank
else {
// Remove the error message
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
You can use event.preventDefault to stop the default action happening. Then check your condition, display errors if the condition fails and submit the form if not.
$("#submit").click(function(event) {
event.preventDefault();
if($(this).val().length === 0) {
// display some error
} else {
$("#myid").submit();
}
});
Really I advice you to use some frameworks for form validation. Because that's the common task and it was already done 100000 times before. There are plenty of it, for example Parsley or Jquery plugin, but there are a lot of others which is simple and easily maintainable, just google 'javascript form validation'
Why is already implemented code better than custom in that case: 1) It already written, tested and working, 2) You almost never need only single validation, and really to validate form for several parameters could be a challenge and could lead to a big amount of validation code 3) framework is DRYer and a really a lot of other stuff.
I also advise you to use validation framework because you need more validation for different field. Use MooTools Floor this is most reliable framework for validation.
MooTool Floor
You can use the HTML5 required='required' option in the input tag...

Using depends with the jQuery Validation plugin

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.

Categories

Resources