Adding validation in kendo datepicker results recusrive call - kendo-ui

I have a datepicker and validation in it's blur event. If validation fails I am showing a message to user and focus the datepicker again. But it becomes recursive.
Message appears all the time. User can't get of the loop unless she kills the page.
(function() {
$("#kendoDatePicker").kendoDatePicker();
$("#kendoDatePicker").on("blur", function() {
if ($(this).data("kendoDatePicker").value() > new Date()) {
alert("Date cannot be greater than today. Please re-enter.");
var datepicker = $(this).data("kendoDatePicker");
datepicker.element.focus();
}
});
})();
<script src="http://cdn.kendostatic.com/2012.2.913/js/kendo.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo-section k-content">
<input id="kendoDatePicker" value="04/04/2017" style="width: 100%" />
</div>
Fiddle is here: https://jsfiddle.net/Hd47F/312/

Well, you said it yourself that you are focusing the datepicker again in the blur event. So, of course it will become recursive. You can put the validation logic inside the form submit event, instead of the datepicker's blur event, or do not focus into the datepicker after the validation.
By the way, you don't even need validation. You can set the maximum date of the datepicker to today's date so that the user can't even choose a date in the future. That will also make it more user-friendly.

Related

Kendo DateTimePicker Manual Entry

I'd like to be able to manually enter a date into the dateTime picker and have it persist to the control.
Example Code: http://jsfiddle.net/awDA4/39/
<script src="http://cdn.kendostatic.com/2013.1.514/js/kendo.all.min.js"></script>
<div>
<input id="datepicker" style="width:200px" />
</div>
$(document).ready(function() {
$("#datepicker").kendoDateTimePicker();
});
Say you enter a date by hand into the control like '08/08/2013'
If you then post the form the start of time (01/01/0001) date is sent
If you pick a time from the time drop down it reverts to the current date
Any ideas what I might be doing wrong?
I thought about marking the input as readonly/disabled but surely you should be able to allow users to type a date by hand.
I needed to include additional parseFormats when initializing the DateTimePicker
$(document).ready(function() {
$("#datepicker").kendoDateTimePicker({
parseFormats: ["MMMM yyyy", "HH:mm", "MM/dd/yyyy"] //format also will be added to parseFormats
});
MM/dd/yyyy was added and I can now manually key in dates with that format

How can I change the style of a div on return from a form submit action in Razor MVC3?

I have a Razor/ASP/MVC3 web application with a form and a Submit button, which results in some action on the server and then posts back to the form. There is often some delay, and it's important that users know they should wait for it to complete and confirm before closing the page or doing other things on the site, because it seems users are doing that and sometimes their work has not been processed when they assume it has.
So, I added a "Saving, Please Wait..." spinner in a hidden Div that becomes visible when they press the Submit button, which works very nicely, but I haven't been able to find a way to get the Div re-hidden when the action is complete.
My spinner Div is:
<div id="hahuloading" runat="server">
<div id="hahuloadingcontent">
<p id="hahuloadingspinner">
Saving, Please Wait...<br />
<img src="../../Content/Images/progSpin.gif" />
</p>
</div>
</div>
Its CSS is:
#hahuloading
{
display:none;
background:rgba(255,255,255,0.8);
z-index:1000;
}
I get the "please wait" spinner to appear in a JS method for the visible button, which calls the actual submit button like this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
});
And my view model code gets called, does things, and returns a string which sets the usermessage content which shows up fine, but when I tried doing some code in examples I saw such as:
// Re-hide the spinner:
Response.write (hahuloading.Attributes.Add("style", "visibility:hiddden"));
It tells me "hahuloading does not exist in the current context".
Is there some way I am supposed to define a variable in the view model which will correspond to the Div in a way that I can set its visibility back from the server's action handler?
Or, can I make the div display conditional on some value, in a way that will work when the page returns from the action?
Or, in any way, could anyone help me figure out how to get my div re-hidden after the server action completes?
Thanks!
Is this done with ajax? I would assume so because the page is not being redirected. Try this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
$("#hahuloading").ajaxStop(function () {
$(this).hide();
});
});
As an aside, you no longer need runat=server.

How to clear jquery validate errors

I'm hijaxing an existing form and POSTing to the server. jQuery validate does most of the validation but if validation fails on the server we return the errors to the client as JSON.
Below is the code that does that:
<script type="text/javascript">
$(function () {
$("form").submit(function (e) {
var $form = $(this);
var validator = $form.data("validator");
if (!validator || !$form.valid())
return;
e.preventDefault();
$.ajax({
url: "#Url.Action("index")",
type: "POST",
data: $form.serialize(),
statusCode: {
400: function(xhr, status, err) {
var errors = $.parseJSON(err);
validator.showErrors(errors);
}
},
success: function() {
// clear errors
// validator.resetForm();
// just reload the page for now
location.reload(true);
}
});
});
});
</script>
The problem is I can't seem to clear the validation errors if the POST is successful. I've tried calling validator.resetForm() but this makes no difference, the error messages added by the showError() call, are still displayed.
Note I'm also using the jQuery.validate.unobtrusive plugin.
You posted this a while ago, I don't know if you managed to solve it? I had the same problem with jQuery validate and the jQuery.validate.unobtrusive plugin.
After examining the source code and some debugging, I came to the conclusion that the problem comes from the way the unobtrusive plugin handles error messages. It removes the errorClass that the jQuery.validate plugin sets, and so when the form is reset, jQuery validate cannot find the error labels to remove.
I did not want to modify the code of the plugins, so I was able to overcome this in the following way:
// get the form inside we are working - change selector to your form as needed
var $form = $("form");
// get validator object
var $validator = $form.validate();
// get errors that were created using jQuery.validate.unobtrusive
var $errors = $form.find(".field-validation-error span");
// trick unobtrusive to think the elements were succesfully validated
// this removes the validation messages
$errors.each(function(){ $validator.settings.success($(this)); })
// clear errors from validation
$validator.resetForm();
note: I use the $ prefix for variables to denote variables that contain jQuery objects.
$("#form").find('.field-validation-error span').html('')
In .NET Core I have the form inside a builtin Bootstrap modal.
For now I'm manually removing the error message spans from their containers, once the modal is starting to show, by using the additional .text-danger class of the error message container like so:
$('#my-form').find('.text-danger').empty();
so that I don't rely on container .field-validation-error that might have been already toggled to .field-validation-valid.
The min.js versions of the libraries jquery.validate and jquery.validate.unobtrusive are loaded via the partial view _ValidateScriptsPartial.cshtml, so I played with them to see what resetForm() / valid() and native html form reset() do.
So in my case $('#my-form').data("validator").resetForm() only resets some validator internals, not the form and it doesn't trigger the onReset() function in the unobtrusive library. The $('#my-form').valid() indeed removes the errors in the modal, but only if the modal is fully shown and valid. The native html form reset() is the only one that triggers both onReset() of unobtrusive library, and then the resetForm() of the validator. So it seems like we need to trigger the native html form document.querySelector('#my-form').reset() to activate the reset functions of both libraries/plugins.
The interesting thing is that the unobtrusive library runs the simple jQuery empty() on the .field-validation-error class (the container of the error span message) only in its onSuccess() function, and not onReset(). This is probably why valid() is able to remove error messages. The unobtrusive onReset() looks like it's responsible only for toggling .field-validation-error class to .field-validation-valid. Hense we are left with a <span id="___-error">The error message</span> inside the container <span class="text-danger field-validation-error">...</span>.
May be I am wrong to clear the errors like this:
function clearError(form) {
$(form + ' .validation-summary-errors').each(function () {
$(this).html("<ul><li style='display:none'></li></ul>");
})
$(form + ' .validation-summary-errors').addClass('validation-summary-valid');
$(form + ' .validation-summary-errors').removeClass('validation-summary-errors');
$(form).removeData("validator");
$(form).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
};
I tried answer given in the comment by AaronLS but not got the solution so I just do it like this.
Maybe helpful to someone.
Here's the code I ended up using to clear/reset all errors. It's possible there's some redundancy in there, but it's working for me.
function removeValidationErrors(frmId) {
var myform = $('#' + frmId);
myform.get(0).reset();
var myValidator = myform.validate();
$(myform).removeData('validator');
$(myform).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(myform);
myValidator.resetForm();
$('#' + frmId + ' input, select').removeClass('input-validation-error');
}
The reason this is still an issue (even 6 years on) is that jQuery Validation doesn't have an event handler for when your form is valid; only for when it's invalid.
Unobtrusive Validation taps into the Invalid handler to add your errors to your Validation Summary elements. (Specifically, any element with data-valmsg-summary=true.) But because there's no Valid handler, there's no way for Unobtrusive Validation to know when they can be cleared.
However, jQuery Validation does allow you to supply your own showErrors method, which is called after every validation check, whether the result is valid or invalid. Thus, you can write a custom function that will clear those validation summary boxes if your form is valid.
Here's a sample that will apply it globally. (You could apply it to specific instances of your validators by using settings, but since I always want this functionality, I just put it in the defaults object.)
$.validator.defaults.showErrors = function () {
if (!this.errorList.length) {
var container = $(this.currentForm).find("[data-valmsg-summary=true]");
container.find("ul").empty();
container.addClass("validation-summary-valid").removeClass("validation-summary-errors");
}
// Call jQuery Validation's default showErrors method.
this.defaultShowErrors();
};
This also has the benefit of clearing the validation summary box the moment your form is valid, instead of having to wait for the user to request a form submission.
I couldn't find this documented anywhere, but you should be able to reset the form by triggering a specific event, reset.unobtrusiveValidation, to which unobtrusive listens.
Example here:
.validation-summary-valid, .field-validation-valid { display: none; }
.field-validation-error { display: block; color: #dc3545 }
.input-validation-error { border: 1px solid #dc3545 }
.validation-summary-errors { background-color: #dc3545; color: #fff; margin-bottom: .5rem; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/4.0.0/jquery.validate.unobtrusive.js"></script>
<form id="testForm">
<div class="validation-summary-valid" data-valmsg-summary="true">
Validation Summary:
<ul><li style="display:none"></li></ul>
</div>
<div>
<label for="first_name">first name:</label>
<input data-val="true" data-val-required="the 'first name' field is required" name="first_name" id="first_name" />
<span class="field-validation-valid" data-valmsg-for="first_name" data-valmsg-replace="true"></span>
</div>
<div>
<label for="last_name">last name:</label>
<input data-val="true" data-val-required="the 'last name' field is required" name="last_name" id="last_name" />
<span class="field-validation-valid" data-valmsg-for="last_name" data-valmsg-replace="true"></span>
</div>
<button type="submit">Submit form (click first)</button>
<button type="button" onclick="$('#testForm').trigger('reset.unobtrusiveValidation')">Reset form (click second)</button>
</form>

Dojo is submitting Extraneous Ajax Requests from disconnected/unrelated controls

I'm experiencing some strange behaviour with checkboxes on a Dojo page. In the code below I have created a search form which makes an Ajax/xhrGet request when the search text is changed - this all works as expected.
However I also have a checkbox on the same page which, when clicked, is also submitting an Ajax request. Since I have not connected the checkbox to the search I have no idea why this is happening.
Is this a bug or is there something more subtle going on here?
Any ideas/suggestions?
TIA,
BrendanC
<script type="text/javascript">
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.Tooltip");
</script>
<div dojoType="dijit.layout.ContentPane" splitter="false" region="trailing"
style="width: 200px;">
<script type="text/javascript"> var srch = dojo.byId ("djsearch"); dojo.connect(srch, "onchange", "getbyname"); </script>
Search
<input dojoType="dijit.form.TextBox" name="dojosearch" value="Find"
trim="true" id="djsearch" propercase="true" style="width: 6em">
<p></p>
Tag Summary
<div id='tagsummary'></div>
</div>
I found the cause of my problem. Hopefully this will help someone else in the future.
Basically I did not issue the dojo.connect correctly - this needs to be done inside the 'addOnLoad' handler. In my initial code I was issuing the connect request on the page, but not in the required addOnLoad handler. The following code works correctly.
Hopefully this will help someone else in the future.
<script>
// Add the dojo.connect below
dojo.addOnLoad(function() {
// Connection s/b in 'addOnLoad' to work correctly
var srch = dojo.byId ("djsearch");
dojo.connect(srch, "onchange", "getbyname");
});
</script>

JQuery for Push-down form

Is there a JQuery plugin that allows me to 'unhide' a form by after clicking a link? Like I have an invite link that can take me to a one text field form for an email address but I want this form to just drop down (pushing the rest of the content down also) and shows the form to submit the email. If you guys can think of a JQuery plugin that lets me do this, please let me know
Edit:
So I did this
<div class='add-link'>
<div id='invite_link'><a href=''>Invite User</a></div>
<div id='invitation_form'>
<form>
<input type='text'/>
</form>
</div>
</div>
and my jquery looks like
<script type="text/javascript">
$(function()
{
$("table").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']});
$('#invitation_form').hide();
}
);
$('#invite_link').click(function() {
$('#invitation_form').slideDown();
});
Do you guys see any error that causes the form not to slide down. It hides the form when the page loads but when I click the link it is not sliding down.
$('a.mylink').click(function() {
$('#MyForm').slideDown();
});
I don't think you need a jQuery plugin for this. The base jQuery library should be sufficient.
$('#showFormLink').click(function () {
$('#form').slideDown();
});
If you're looking for animation, that's possible as well by passing in a duration argument to slideDown.
Take a look at the jQuery show documentation.

Resources