0

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. :)

MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119
  • 1
    Definitely not a duplicate of that question. This question relates specifically to use of the `genvalidator` javascript plugin. – cssyphus Oct 08 '13 at 22:49

6 Answers6

1

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.

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Thanks for the detailed reply. I tried your first example and adapted to my case.. but the check doesn't seem to be operative: http://pastebin.aquilenet.fr/?6890f0495460d9b7#Fs9OEiKmG6NW/S4WIeAVULVJlMWjcNXqgrN7BtxEkGU= – MultiformeIngegno Oct 09 '13 at 23:14
  • 1
    @MultiformeIngegno Please see my response at the bottom of my answer above. It is a long response; please read carefully. – cssyphus Oct 10 '13 at 16:17
  • You're welcome. I hope it is helpful (and I hope you study the example carefully). Best wishes with the rest of your project. – cssyphus Oct 10 '13 at 23:20
0

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;
} 
joe42
  • 657
  • 4
  • 12
  • I tried both functions but the form still passes if checkbox isn't checked. – MultiformeIngegno Oct 08 '13 at 22:15
  • How are you calling validate and how are you submitting the form? is frmValidator handling the submission after validation and if so, do they have a callback that you can use to submit the form yourself? – joe42 Oct 08 '13 at 22:17
  • `if(empty($name)||empty($visitor_email)||BLAHBLAH) { $errors .= "\n Mandatory field "; } if(IsInjected($visitor_email)) { $errors .= "\n Email format wrong"; } if(empty($errors)) { .... function to sendmail} ` – MultiformeIngegno Oct 08 '13 at 22:21
0

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.

talemyn
  • 7,822
  • 4
  • 31
  • 52
0

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

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • I tried your code but a genvalidator popup appeared telling me: Pass the function name like this: validator.setAddnlValidationFunction(DoCustomValidation) rather than passing the function name as string I replaced frmvalidator with validator but doesn't work... the form goes also if checkbox isn't checked.. – MultiformeIngegno Oct 08 '13 at 22:12
  • Did you try: `frmvalidator.setAddnlValidationFunction("DoCustomValidation");` ? *See the link in my answer to genvalidator documentation (source). That is where I obtained the syntax.* Do not replace `frmvalidator` with `validator` -- in your posted code at top you are using `frmvalidator`, yes? – cssyphus Oct 08 '13 at 22:54
  • Yep all the code posted at top I'm using frmvalidator. When I try with frmvalidator I get that error message. You can see the form live at http://www.rendezvousroma.it/new/contatti.php (can leave it some minutes) – MultiformeIngegno Oct 08 '13 at 23:04
  • What's that "document.form1." ? – MultiformeIngegno Oct 09 '13 at 20:19
  • That is from the js code you posted in the OP (original post). I presumed it was the correct javascript to access the value of the `input#agree` element. You can test that using an alert: `alert(document.form1.agree.checked)`. See [this jsFiddle](http://jsfiddle.net/WnjkE/) *You should also upvote some of the answers that have been helpful to you thus far...* – cssyphus Oct 09 '13 at 21:26
  • 1
    Please review a new answer I posted for you regarding using jQuery for manual validation checking. Honestly, it's easier than what you are trying to do - and you have more control over the process. – cssyphus Oct 09 '13 at 22:07
0

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

Opal
  • 81,889
  • 28
  • 189
  • 210
Kiara
  • 117
  • 1
  • 1
  • 11
0

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