Skip to content

Instantly share code, notes, and snippets.

View danielgreen's full-sized avatar

Daniel Green danielgreen

  • Glasgow, United Kingdom
View GitHub Profile
@danielgreen
danielgreen / jquery.validate.submithandlerfix.js
Created May 29, 2013 09:59
This is an amended fragment of jquery.validate.js (https://github.com/jzaefferer/jquery-validation). The change is to take the value returned from validator.settings.submitHandler.call, and return that value from the handle function. This means that a page that uses submitHandler to take some action upon a successful validation can simply return…
// validate the form on submit
this.submit( function( event ) {
if ( validator.settings.debug ) {
// prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden;
if ( validator.settings.submitHandler ) {
if (validator.submitButton) {
@danielgreen
danielgreen / jquery.unobtrusive-ajax.errorfix.js
Created May 29, 2013 10:35
This is an amended fragment of Microsoft jQuery Unobtrusive Ajax (http://nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax). The change is to the error property, to ensure that it calls .apply() to invoke the function specified by the data-ajax-failure attribute. Previously it did not call .apply() hence the error handler specified by the pag…
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
if (result !== false) {
loading.show(duration);
}
@danielgreen
danielgreen / AssertValueAttribute.cs
Last active December 17, 2015 20:39
AssertValue is a validation attribute (i.e. a data annotation) that can be applied to a property of a view model class. It causes the property to be invalid unless it has the value specified in the attribute's constructor. The attribute implements IClientValidatable which ties it up with client-side JavaScript in order to replicate the validatio…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Validators
{
@danielgreen
danielgreen / ValidateHiddenFields.js
Last active October 26, 2023 14:19
The jQuery Validation plugin does not validate hidden fields by default. Here is how to get around that.
// By default, the jQuery Validation plugin ignores hidden fields. You may want them to be validated however.
// The default 'ignore' setting is ':hidden'
// See https://github.com/jzaefferer/jquery-validation/issues/189
// Attach a validator to a particular form, with a blank 'ignore' setting.
// If you are using Unobtrusive Validation then you can't do this, as the Unobtrusive script initialises the plugin for you.
// Instead, you must either amend the setting on the validator once it's attached to the form,
// or amend the default setting before the validator is attached (read on to see how).
$("MyForm").validate({ ignore: "" });
@danielgreen
danielgreen / AjaxResultAttribute.cs
Last active January 15, 2018 08:36
ASP.NET MVC does not help you to display validation errors, perform browser redirects, or update the UI if the browser postback used Ajax instead of a normal form post. The following code deals with these situations using Knockout. Use ajax_ProcessSuccess as the OnSuccess callback for Ajax.BeginForm (see http://bradwilson.typepad.com/blog/2010/1…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Web.Json;
namespace Web.Filters
@danielgreen
danielgreen / AjaxRequestAttribute.cs
Created May 29, 2013 12:49
A filter that can be applied to an MVC action to specify that either Ajax or non-Ajax requests should not be allowed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace SFR.TOR.Web.Filters
{
/// <summary>
@danielgreen
danielgreen / submitHandler.ClearValidationSummary.js
Last active December 17, 2015 20:49
The jQuery Validation library apparently does not clear or hide the Validation Summary list after a successful validation. If the form is valid and will be submitted to the server, it looks better to hide the list. Use a submitHandler callback to deal with this.
// Set the submitHandler callback via the settings object, as is necessary if you are using Unobtrusive Validation.
// If you are not using Unobtrusive Validation then you can set submitHandler in the options object passed to validate().
$("#iTrentExportForm").validate().settings.submitHandler = function (form) {
BlockPage(); // you may want to block the page during the Ajax call
var container = $(form).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length) {
list.empty();
@danielgreen
danielgreen / invalidHandler.UnobtrusiveValidation.js
Created May 29, 2013 14:02
When using jQuery Validate, you may want to run some code when it detects that the form is invalid. When using Unobtrusive Validation, you don't have the ability to set invalidHandler directly when initialising the Validate plugin, so here is a workaround.
// If using Unobtrusive Validation then that library initialised the Validate plugin
// on our behalf, so we missed the chance to set invalidHandler. Even if we were to
// set invalidHandler now via the settings object it would have no effect, due to the
// way that Validate works internally. Instead, we can do the following:
$("#MyForm").bind("invalid-form.validate", function () {
// Do something useful e.g. display the Validation Summary in a popup dialog
$("div.ValSummary").dialog({
title: "Information",
modal: true,
resizable: false,
@danielgreen
danielgreen / ParseJSONDates.js
Last active March 8, 2021 22:26
When an ASP.NET MVC 4 action returns JSON containing a DateTime value, the value is serialized into a format that cannot be natively understood by JavaScript. Here is some code to process the value into a JavaScript Date. A better solution than this is to use JSON.NET to serialize dates instead. See https://gist.github.com/danielgreen/5669903
function dateTimeReviver (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
}
@danielgreen
danielgreen / FormatJavaScriptDate.js
Created May 29, 2013 14:39
Formatting JavaScript dates. Unashamedly nicked from https://gist.github.com/atesgoral/1005948 via http://www.140byt.es/keywords/date. See the linked Gist for more documentation. Alternatively see www.datejs.com and momentjs.com
function formatDate (d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})}
// Formats the date as a string e.g. "24/08/2013 17:04"
var formattedDate = formatDate(parsedDate, "{Date:2}/{Month:2}/{FullYear} {Hours:2}:{Minutes:2}");
//Instead of using classical format specifiers like "YYYY", "MM", "HH", "mm" etc.
//this function uses the Date instance getters like getFullYear, getMonth, etc.
//with support for zero-padding.
//For example, instead of: