-1

I use jQuery Validation Plugin and I want to validate some hidden/disabled fields besides the other fields. Although every fields can be validated properly, I have some trouble with the hidden/disabled fields. At this point:

1) I hide a Textbox field according to the value of a Dropdownlist selected value. Which method is better for validating this field: disabled=true/false or hide/show? Or both of them at the same time?

2) For the Textbox field that will be hidden/disabled according to the Dropdownlist value, should I make this Required in the related Entity model as the other ones? If yes, the same field is assumed a mandatory field and tried to be validated even if it is hidden/disabled.

3) On the other hand, when I do not use required for the related field on in the Entity model, it is not validated even if I typed it as below:


jQuery(function () {
    $("#myform").validate({
        onfocusout: false,

        rules: {
            'Applicant.workingSoot': "required"
        },

        messages: {
            'Applicant.workingSoot': {
                required: "Make is required!"
            }
        },

        submitHandler:
            $("#myform").on('submit', function () {
                if ($("#myform").valid()) {
                    //Do something here
                    alert("Validation passed");
                }
                return false;
            })
    });
});


Note: I use the javascripts for validation with the given order below:

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>



UPDATE

Layout.cshtml:

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


View:

<script type="text/javascript">   

    //It is used for show/hide fields according to the related 
Dropdownlist selected value
    function showHideWorking() {
        var $index = $('#isWorking').val();
        if ($index == '31') {          
            $('#workingSoot').show(); 
            $('#lbworkingSoot').show(); 
            $('#workingCity').show(); 
            $('#lbWorkingCity').show(); 

            //disabling fields in addition to hiding
            $('#lbworkingSoot').disabled = false;
            $('#workingCity').disabled = false;
            //            
        }
        else {
            $('#workingSoot').hide(); 
            $('#lbworkingSoot').hide();
            $('#workingSoot').val(""); 

            $('#workingCity').hide(); 
            $('#lbWorkingCity').hide(); 
            $('#workingCity').val(""); 

            //disabling fields in addition to hiding
            $('#lbworkingSoot').disabled = true;
            $('#workingCity').disabled = true;
            //
        }
    }
</script>

<script type="text/javascript">
/* <![CDATA[ */   /* Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA. */
jQuery(function () {

    $.validator.setDefaults({
        // options for all forms on page
    });

    $("#addForm").validate({
        onfocusout: false,

        rules: {
            'Applicant.identityNumber': "required",
            'Applicant.name': "required",
            'Applicant.surname': "required",
            'Applicant.telephone': "required",
            'Applicant.email': "required",
            'Applicant.organization': "required",
            'Applicant.hasDoneAnyProject': "required",
            'Applicant.isInterestedAnyProgramme': "required",
            'Applicant.meetingId': "required",
            'Applicant.isWorking': "required",

            //displayed & hidden fields:
            'Applicant.workingSoot': "required",
            'Applicant.workingCity': "required" 
        },

        submitHandler:
            $("#addForm").on('submit', function () {
                if ($("#addForm").valid()) {
                    //Do something here
                    alert("Validation passed");
                }
                return false;
            })
    });
});
/* ]]> */


@using (Html.BeginForm("Add", "Applicant", FormMethod.Post,
new { id="addForm", enctype = "multipart/form-data" }))
{    
    <div class="container">
        <fieldset>
            @Html.LabelFor(m=>m.Applicant.IdentityNumber)
            @Html.TextBoxFor(m => m.Applicant.IdentityNumber, new { maxlength = 11, name = "identityNumber", id = "identityNumber", @class = "numbers_only" }) 
            @Html.ValidationMessageFor(m => m.Applicant.IdentityNumber, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Name)
            @Html.TextBoxFor(m => m.Applicant.Name, new { maxlength = 30, name = "name", id = "name", @class = "letters_only" })
            @Html.ValidationMessageFor(m => m.Applicant.Name, null , new { @class = "ValidationErrors" }) 

            @Html.LabelFor(m=>m.Applicant.Surname)
            @Html.TextBoxFor(m => m.Applicant.Surname, new { maxlength = 30, name = "surname", id = "surname", @class = "letters_only" })
            @Html.ValidationMessageFor(m => m.Applicant.Surname, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Telephone)
            @Html.TextBoxFor(m => m.Applicant.Telephone, new { maxlength = 11, name = "telephone ", id = "telephone", @class = "phone_uk" })
            @Html.ValidationMessageFor(m => m.Applicant.Telephone, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Email)
            @Html.TextBoxFor(m => m.Applicant.Email, new { maxlength = 50, name = "email", id = "email" })
            @Html.ValidationMessageFor(m => m.Applicant.Email, null , new { @class = "ValidationErrors" })
        </fieldset>

        <fieldset>
            @Html.LabelFor(m=>m.Applicant.IsWorking)
            @Html.DropDownListFor(m => m.Applicant.IsWorking, new SelectList(Model.Lookups.Where(x => x.LookupType == "Working"),
           "LookupID", "LookupValue"), "---- Select ----", new { name = "isWorking", id = "isWorking", onchange="showHideWorking()"}) 
            @Html.ValidationMessageFor(m => m.Applicant.IsWorking, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.WorkingSoot, new { name = "lbworkingSoot", id = "lbworkingSoot" })
            @Html.TextBoxFor(m => m.Applicant.WorkingSoot, new { maxlength = 50, name = "workingSoot", id = "workingSoot" })
            @Html.ValidationMessageFor(m => m.Applicant.WorkingSoot, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.WorkingCity, new { name = "lbWorkingCity", id = "lbWorkingCity"})
            @Html.DropDownListFor(m => m.Applicant.WorkingCity, new SelectList(Model.Cities,
           "CityID", "CityName"), "---- Select ----", new { name = "workingCity", id = "workingCity"}) 
            @Html.ValidationMessageFor(m => m.Applicant.WorkingCity, null , new { @class = "ValidationErrors" })
        </fieldset>      

        <input id="submitbtn" type="submit" value="Send" class="button" />
    </div>     
}
3
  • You need to show a code attempt. Also, where is the HTML markup?
    – Sparky
    Dec 16, 2013 at 23:47
  • @Sparky: I had looked at the page you mentioned, but it is not related to my situation. I added the code. Can you have a look at pls?
    – Jack
    Dec 18, 2013 at 20:04
  • HTML markup as rendered in the browser.
    – Sparky
    Dec 18, 2013 at 20:11

2 Answers 2

1
  • submitHandler takes a function as a parameter which specifies what to do when your form is successfully validated. For example:

     submitHandler:function(form){
           alert('Validation passed');
     }
    
  • By default jQuery Validate does not validate hidden fields. So if you hide a field based on the value of a dropdown, it will not be validated in any way.

5
  • My question is not related to the submitHandler part. Could you please have a look at the questions and try to enswer them one by one?
    – Jack
    Dec 16, 2013 at 22:32
  • I answered all 3 parts of your question in my 2nd point. At least, I think I did...
    – Ryley
    Dec 16, 2013 at 22:42
  • But it does not work as it had not before I asked the question...
    – Jack
    Dec 16, 2013 at 22:51
  • 1
    Your question was whether hiding the field prevents it from being validated, the answer to which is "yes". If you make it required, this does not matter, as it will not be validated. So problem solved?
    – Ryley
    Dec 16, 2013 at 23:24
  • Ryley: I added the updated code. Can you have a look at pls?
    – Jack
    Dec 18, 2013 at 20:05
0

You seem to not understand how the submitHandler callback function works...

submitHandler:                               // <- "function() {" is missing
    $("#myform").on('submit', function () {  // <- redundant
       if ($("#myform").valid()) {           // <- redundant
          //Do something here
          alert("Validation passed");
        }
        return false;
     })
                                             // <- closing brace } is missing
  • You're missing the function() and braces, { }, as part of the callback. Should be

    submitHandler: function(form) {
        ...
    }
    
  • The submitHandler only fires upon the click event of the submit button (when the form is valid) so there is absolutely no way you would ever need to put a .on('submit') handler inside of this. I doubt it could ever work because the plugin is blocking the default submit event so it can validate the form.

  • And since the submitHandler only fires when the form is valid (on button click), there's no need to test it again using if .valid().

Removing all the redundancy in your code...

submitHandler: function(form) { // only fires on button click when form is valid 
    // Do something here
    alert("Validation passed");
    return false;
}

By default, this plugin will ignore all hidden fields. To enable validation on hidden fields, set the ignore option as follows...

ignore: []

If you want to toggle validation rules based upon something else, use the depends method or add/remove rules dynamically with the .rules('add') and .rules('remove') methods.

However, since you haven't really shown what you want to do, nor have you shown any HTML markup, I can only recommend that you study the documentation and review the hundreds of code examples posted on Stack Overflow.

Not the answer you're looking for? Browse other questions tagged or ask your own question.