JQuery Validation Doesn't Work After Page Refresh (JQuery Mobile)

I have a jQuery Mobile / asp.net mvc4 application. After the first page, subsequent pages call jQuery mobile using Ajax requests. Now I used the Validator plugin for jQuery to perform validation on my forms, validating for the first time (i.e. when loading using ajax calls), but when the page refreshes / reloads, validation does not work. Any idea why this is happening? Since this is a mobile web application, users can refresh pages.

this is the verification code i used:

<script type="text/javascript"> // jquery form validation function $(function () { $("#permissionRequestForm").validate({ errorPlacement: function (error, element) { if (element.attr("name") === "fromTimeHH" || element.attr("name") === "toTimeHH" || element.attr("name") === "fromTimeMM" || element.attr("name") === "toTimeMM") { error.insertAfter($(element).parent()); } else { error.insertAfter(element); } }, //custom validation messages messages: { fromDate: "Choose From Date", toDate: " Choose To Date", fromTimeHH: "Choose From Time", fromTimeMM: "", toTimeHH: "Choose To Time", toTimeMM: "", permissionTypeOne: "Select Permission Type", permissionTypeTwo: "Select Permission Type", approverList: "Select Approver", reasonLeave: "Enter a Valid Reason" } }); }); 

+4
source share
1 answer

This is a wild assumption because no sample code was provided, I suppose you used:

 $(document).ready(function() { }); 

to initialize the validation plugin, which is common practice for jquery. Unfortunately, the finished document cannot be used with jQuery Mobile.

Also do not use:

 $(function () { }); 

With jQuery Mobile.

The Validator plugin must be initialized in the show show event, for example:

 $('#index').live('pageshow',function(e,data){ $.validator.addMethod("valueNotEquals", function(value, element, arg){ return arg != value; }, ""); $("#form1").validate({ rules: { select_list : {valueNotEquals: "default"}, }, messages: { select_list : { valueNotEquals: "You must select a value" } }, submitHandler: function(form) { alert($('#form1').valid()); form.submit(); } }); }); 

And here is a working example: http://jsfiddle.net/Gajotres/AZPhK/ . No matter how much time you close and return to the first page, every time the page is displayed, the validator will be initialized.

EDIT:

IF you use HTML format with several html, put this code only in the necessary page or, better, create a new js file, put this code (all your custom js code) into it and share it with all html pages.

+3
source

All Articles