The software development blog of James "poprhythm" Kolpack RSS 2.0
# Saturday, September 11, 2010

In Jon Galloway’s Splitting Camel Case with RegEx blog post, he introduced a simple regular expression replacement which can split “ThisIsInPascalCase” into “This Is In Pascal Case”.  Here’s the original code:

output = System.Text.RegularExpressions.Regex.Replace(
    input,
    "([A-Z])",
    " $1",
    System.Text.RegularExpressions.RegexOptions.Compiled).Trim();

Simple and effective.  Matches any capital letters and inserts a space before them.  But there’s room for improvement.  First, the call to String.Trim() to remove any spaces potentially added if the first letter is uppercase – this can be handled with a “Match if prefix is absent” group containing the “beginning of line” character ^.  This prevents any matches from occurring on the first character, which eliminates the need for the String.Trim() call.  The formal name for this grouping construct is “Zero-width negative lookbehind assertion”, but just think of it as “if you see what’s in here, don’t match the next thing”.

    (?<!^)([A-Z])

Next - there’s a potential issue with how acronyms get handled with this.  Given this fictional book title: “WCFForNoobs” – the split will occur on each uppercase letter resulting in “W C F For Noobs”.  The fix is simple, though – require that uppercase letters be followed by a lowercase:

    (?<!^)([A-Z][a-z])

…Now it’ll result in “WCF For Noobs” (aren’t we all!).  But now it won’t add a space before the acronym – for “LearnWCFInSixEasyMonths”, the result will be “LearnWCF In Six Easy Months”.  No problem – add an alternate match for a lowercase letter coming before the uppercase letter.  The replace pattern makes this more difficult – we don’t want the space to go before the lowercase letter, we want it between the lowercase and the first capital letter of the acronym.  RegEx can handle this with another lookbehind match group – “Match prefix but exclude it” - (?<=).  This allows the match to occur on the lowercase-uppercase pair, but only the uppercase portion will get matched, so when it comes time to run the replacement, the space will get inserted between the two letters.  By itself, that’ll look like this:

    ((?<=[a-z])[A-Z])

Great!  But this needs to be combined with previous expression.  Easy accomplished with an either/or match using the vertical bar “or” construct:

    (?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])

The example “LearnWCFInSixEasyMonths” will now be split into “Learn WCF In Six Easy Months”.  These same techniques can be used for additional splits – perhaps on numbers or underscores.  More generally, lookbehind and lookahead are great tools to have in your RegEx toolbelt.

Saturday, September 11, 2010 10:03:15 PM (Eastern Daylight Time, UTC-04:00)  #   
Comments [0] -
# Friday, August 27, 2010

With tongue implementation injected dynamically into cheek objectReShephard

ReSharper is my shepherd,
I shall not want;
He lets me apply quick refactors.
He leads me to errors before compile;
He cleans up my code.
He navigates me in paths of inheritance
for each namespace.

Even though I strive to remove cruft
of the brownfield app,
I fear no error;
for You are in my IDE;
Your red and Your green unit tests, they comfort me.

Surely correctness and maintainability shall follow me
all the deployments of my app;
and I shall dwell favorably in the thoughts of my
Users forever.

Sum(23)

Friday, August 27, 2010 5:19:31 PM (Eastern Daylight Time, UTC-04:00)  #   
Comments [0] -
# Sunday, June 27, 2010

This last week I gave two presentations at CodeStock 2010.  Thanks to everyone attended my sessions, hope you got something out of them, and thanks to the CodeStock organizers for all your hard work.  Here’s some content from the presentations:

Sunday, June 27, 2010 8:21:01 PM (Eastern Daylight Time, UTC-04:00)  #   
Comments [0] -
# Saturday, May 22, 2010

Double face palm

Digging around in some code circa 6 months ago I discovered a method that I had scrounged from the web and, in my apparent haste at the time, had not build any unit tests.  It was less than 20 lines of code doing some simple array manipulation – and it was from a pretty decent site, so it seemed pretty safe.  It’s the weekend so I thought, hey, time to plug that gap!  I started with some simple cases and soon realized that one of the execution paths was just … well, plain wrong.

Luckily, that behavior wasn’t being used anywhere in my project (yet!), but still, it was essentially a land mine waiting for someone to trip it.  My first reaction was “shame on them for posting that without testing it!”  Of course, this code didn’t end up in my project because of the author.  It was I who blindly accepted and given it the “it’s from the internet!”-stamp-of-approval.

Lessons learned today:itsfromtheinternet

  • Trust is earned, not given.
  • Source code becomes trusted by-way-of thorough unit and functional testing.
  • Do not trust untested code from the internet.
  • Do not trust untested code from your own keyboard even more so – at least on the internet it’s likely that someone else has reviewed it.

I’ve written the author a friendly note with a simple fix – it’s better to diffuse that bomb than let it get somebody else!

Saturday, May 22, 2010 10:51:48 PM (Eastern Daylight Time, UTC-04:00)  #   
Comments [3] -
# Tuesday, March 23, 2010

I’m feeling a bit guilty about some code I wrote:

using (new OperationTimer("MyOperation", this))
{
    // ... complete operation
}

This innocent looking C# snippet is hiding a tricky secret - the using statement is being misused (no pun intended).  The documentation defines the intended usage clearly:

using Statement
Defines a scope, outside of which an object or objects will be disposed.

The problem?  The notion of “object disposal” is being hijacked!  In your garden variety IDisposable implementation, you’d be dealing with an external resource that needs to be released before the object can be removed from memory.  Instead, I’m using it to time a block of code like so:

class OperationTimer : IDisposable
{
    private readonly string _operationName;
    private readonly ITimable _obj;
    private readonly Stopwatch _stopwatch;

    public OperationTimer(string operationName, ITimable obj)
    {
        _operationName = operationName;
        _obj = obj;
        _stopwatch = new Stopwatch();
        _stopwatch.Start();
    }

    public void Dispose()
    {
        _stopwatch.Stop();
        _obj.OnOperationCompleted(_operationName, _stopwatch.Elapsed);
    }
}

The constructor starts a timer and the Dispose() method stops it and reports the elapsed time.  (aside: if you’re interested in how I’m using the timer, check out my previous article Simplified Performance Counters) There are certainly other ways to accomplish this same behavior, but they lack the elegance of a neatly scoped code block.  It’s arguably an acceptable way to repurpose the language.  In fact, the ASP.NET MVC authors saw fit to use it in a similar fashion with the BeginForm helper.  The only “resource” it disposes of is to render a closing </form> tag.

My question is: When does repurposing language constructs turn from “acceptable language use” to a “dirty trick”, or worse, “illegible line noise”?

It seems like a slippery slope.  One instance that I don’t care for is controlling execution flow by-way-of logical operator precedence in most C-like languages:

expression1 && expression2 || expression3

Which is equivalent to:

if (expression1)
    expression2
else
    expression3

This takes advantage of the order of evaluation in a logical statement – it is assumed (correctly) that expression2 will never be evaluated if expression1 is evaluated as false, and instead, expression3 will get to run.  Likewise, if the first two evaluate to true, the truth value is known for the statement and expression3 is never evaluated. This is clearly not the intended usage which the language designers had in mind, but it works, and it saves any keywords from being written.

Some truly beautiful code has been written by way of hijacking the language.  For instance, here’s a program that will calculate the value of pi using an ascii circle.  Truly neat - but also completely useless from a software development standpoint.

What do you think?  Should I just get over my guilt about repurposing IDisposable?  Or, should I be true to the original intent of the language and find another way?

Tuesday, March 23, 2010 8:06:11 PM (Eastern Standard Time, UTC-05:00)  #   
Comments [3] -
# Saturday, March 20, 2010

I just posted an article on CodeProject about a generalized code block which can be used in a common scenario for simple performance benchmarking.  Check out "Simplified Performance Counters for Timed Operations" here

OperationPerformanceCounter_AddCounters OperationPerformanceCounter_OperationsPerSecond OperationPerformanceCounter_AverageDuration

Saturday, March 20, 2010 9:00:54 PM (Eastern Standard Time, UTC-05:00)  #   
Comments [0] -
# Sunday, February 28, 2010

As software developers we are forever scheming on ways to increase the quality of our software.  It’s a great feeling when customers are enjoying some bit of code that you wrote, so making it even better next time is a worthwhile goal.  In contrast, I’ve observed at a number of SaaS development shops have a lack of quality when it comes to the delivery mechanics.  It’s as if once the software is written, the development effort is over and it’s time to tediously prepare for the deployment ceremony.  What I want to write about is the deployment process itself – there’s a whole other topic relating to deployment project management which includes tracking changes, scheduling – perhaps another day on that.

The fact is that many software shops will deploy their services manually.  This may (hopefully) include multiple environments for development, QA, staging, and finally production.  Deployments will have checklists looking something like:

  1. Log into target machine.
  2. Shut down service.
  3. Copy updated binaries.
  4. Make any configuration changes.
  5. Restart service.
  6. Repeat for every target.

If the application has data/schema updates, it could be added as another step in the deployment process.  Likewise, in a multi-target environment there may be preliminary steps for switching out the targets from an application pool.  Finally, in the case of a software emergency, a working roll-back strategy is essential.  A few points:

  • Deployment is time consuming
    • While each step may only take a few minutes, together it can add up to a significant chunk of a work day.  Multiply that by the target count for the environment - lather, rinse, repeat.
  • Steps are error prone
    • A missed or botched step may not be noticed until it’s time to turn on the service – or worse, afterwards.  There’s a lot of click-click-typedy-typedy-clicking with not a lot of feedback.
  • None of the steps actually require human interaction
    • I have never seen a deployment plan where all of the steps and details were not known before hand.  If the plan is not 100% deterministic, it’s probably more of a deployment idea and should be re-thunk’d.

Automating the deployment seems like a no-brainer.  Ayende Rahien makes his views clear -

If you don't have an automated deployment, it generally means that you are in a bad position. By automated, I mean that you should be able to push a new version out by double clicking something. If you can't get automated deployment script in under an hour, you most certainly have a problem.

But how to get from source code to having it automatically deployed?  It takes a bit of setup, but it’s well worth the effort for a project in active development.  Here’s one potential dataflow:

 Service Development Workflow

  1. Code gets written for the project and placed in source control
    • All code needs to be in source control – no exceptions!
  2. Continuous integration triggers a build
  3. Builds artifacts are created by the build server
  4. Project configurations for each potential target
    • This includes setting environmental variables and injecting any content needed to make the code run correctly once it is deployed
  5. Automated Deployment
    • This is essentially a scripted equivalent of the manual deployment process

There are many open source and commercially available technologies catering to each of these functions – I’ll dig into a few of them in some future posts.  In broad terms, it’s a worthwhile endeavor to have an end-to-end software delivery process.  It’s a guarantee that your time and energy are kept focused on doing what’s important – developing software!

Sunday, February 28, 2010 10:03:24 PM (Eastern Standard Time, UTC-05:00)  #   
Comments [0] -
# Sunday, January 10, 2010

Being a Resharper user for the past 5 years, I had to jump on opportunity to try out the publicly released beta for the new 5.0 version.  I’m currently using Visual Studio 2008, but I’ll be glad to have the updated VS2010 support from Resharper once it’s released.  As for the changes in this major revision, I’m excited to try out new code inspections, LINQ integration improvements, and native NUnit integration.

Installation

  • Resharper5BetaInstallCompleteInstall was quick and easy.  It uninstalled the version 4.5 and questioned me about killing a task that was getting in the way.
  • Starting Resharper, I’m greeted with a “License to version 4.0 is not acceptable”.  This is troubling in two ways:
    • The license that I bought is for 4.5 C# Edition.
    • Why does a beta need a license?
      Resharper5BetaLicense
    • For now, using “free evaluation” – this seems to do the trick.
  • As expected, the AgentSmith plugin is no longer installed (duh), but an updated version is available on their site.

New Features

I’d like to be pretty thorough in acquainting myself with the enhancements, so I’ll touch on each of them from the list here.

  • Structure Patterns image
    • Custom built code refactorings.  This could be a godsend for brownfield development – enabling project-wide cleanup for stinky “code smells”.  The real power is in the “Placeholder” templating – it’s much like the Live Templates but for refactoring.  The image onthe right has a pattern that I made to change from timeSpan to happyHour.  Needless to say, this is trivial (and useless!), but I’m readily awaiting the next time I find a code smell I can’t live with.
  • Project Refactoring and Dependencies View
    • I’ve been waiting for the ability to mass-rename namespaces.  Resharper5 : check. 
    • So what does “Project Refactoring” mean?  Does a project have a bunch of types declared in the same files?  After a few clicks, they can all moved into their own:image
      image 
    • Dependency View is basically “find usages by project” – which could certainly be useful for larger solutions. 
  • Call Tracking, Value Tracking
    • Examines method, variable, field or property usage through the solution and finds where it’s being generated or called from, as well as the opposite - where it’s being used.  It’s the static-analysis version of the call stack.
      image
  • Internationalization
    • I’ve never worked on a project using Internationalization, but it’s bound to happen sooner than later. Resharper 5 adds the ability to move string to resource files as well as refactoring and inspection to support multiple languages.
  • ASP.NET
    • imageSyntax highlighting!  Check it out - unused namespaces inside ASP.NET markup will now appear grayed out, just as they do in source code.
    • Templates for ASP.NET:
      image
  • ASP.NET MVC
    • imageView name autocomplete from the controller, as well as navigation to and from actions.
    • … and navigation to Views.  Shift+Click on a view name to jump there:
      image
    • Aside: Our project has some calls to HtmlHelper.RenderPartial(“<ViewName>”) called inside of a class instantiated with an instance of HtmlHelper (it’s a Helper for HtmlHelper). Resharper can’t resolve these names… but I wouldn’t expect it to.
  • IntelliSense Changes
    • In addition to performance improvements, completion can now done using abbreviated names based on CamelHumps:
       image
  • imageBookmarks
    • Set and jump to bookmarks with quick keystrokes.  Ctrl+Shift+[0-9] to set, and Ctrl+[0-9] jump back.  Ctr+~  to see which bookmarks are available:
       image
  • Upgrade to LINQ
  • New and Improved Code Inspections
    • So, JetBrain’s says they’ve added a bunch of new code inspections – I’m counting a little over 100 C# Context Actions in 5.0, where as 4.5 had closer to 80.  There appear to be some LINQ related ones in there. They’ve also called out that it can now highlight errors in XML comments (something which the AgentSmith plugin already did quite well).
  • imageNative NUnit Support
    • To be honest, I’ve been using the previous Resharper version’s NUnit support without complaint.  I’m thinking that the that the improvements are “under the hood” – it works just as well now as it did before.
  • XML Formatting
    • Inspection and refactoring support - “Reorder attributes” and “Collapse Empty Tag”, for instance.
      imageimage  
  • imageExternal Sources
    • This promises to add navigation to referenced libraries that before could only be accessed at the higher namespace-class-method  level via Visual Studio’s Object Browser.  I poked around a bit on JetBrain’s site looking how to configure the symbol locations, but it doesn’t seem to be documented yet.  Perhaps it might need to have the symbols locations populated in VS->Options->Debugging-Symbols, but perhaps not.

Surprises

  • Transparently imported settings from 4.5 – horray!  Appears to be able to use the 4.5.resharper shared solution settings
  • imageRunning “Find Usages” on a class is taking much longer – in previous version it was instantaneous, now it appears to be scrounging through files instead of an index (could be External sources feature?)
  • Quick navigate to Type/Filename/Symbol now match partial names – no more needing to put in a “*” to match wildcards.
  • In the day or two I’ve been using it, I don’t think I’ve encountered any crashes.  This is a good thing – the multitude of errors being automatically reported seem to be going to good use.

Wish List

  • Javascript.  Being a dynamic language and all, it’d be pretty difficult to implement the full set of navigation and refactoring helpers Resharper provides for C# and VB.  But oh, wouldn’t it be slick if it could.
  • Community sharing for code-style and and structure patterns. There’s already preference and template sharing with team members via a shared settings file. The next evolution is to extend this to the cloud and create a public library to exchange ideas with all Resharper users.

For every one of the new features I’ve encountered in the past couple of days, I’m sure there are two or three that I haven’t stumbled over yet.  That’s a great thing about this product – utilizing a small subset of it’s features can greatly streamline development and increase productivity.  Even after years of use, I am still happily surprised to discover new facets of the tool I hadn’t noticed or investigated before.

Sunday, January 10, 2010 9:21:29 PM (Eastern Standard Time, UTC-05:00)  #   
Comments [2] -
# Monday, January 04, 2010

From ASP.NET MVC in Action section 4.4.1:

Views are difficult to unit test, so we want to keep them as thin as possible. … Notice in [the View Model] that all of the properties are strings. We’ll have the [properties] properly formatted before this view model object is placed in view data. This way, the view need not consider the object, and it can format the information properly.

To facilitate the formatting between the Domain Model and the View Model, a few of AutoMapper’s features may be utilized. Here’s a DomainModel containing a CurrencyProperty which will needed to formatted for human consumption:

public class DomainModel
{
    public decimal CurrencyProperty { get; set; }
}

Now, here is a ViewModel which will be used to transport the formatted value to the View:

public class ViewModel
{
    ///<summary>Currency Property - formatted as $#,###.##</summary>
    public string CurrencyProperty { get; set; }
}

Mapping from Domain Model to View Model

AutoMapper provides an easy way to create a mapping between two object types.  For particular tweaks for individual property mappings, the ForMember method can be used like:

///<summary>Setup mapping between domain and view model</summary>
static ViewModel()
{
    // map dm to vm
    Mapper.CreateMap<DomainModel, ViewModel>()
      .ForMember(vm => vm.CurrencyProperty, mc => mc.AddFormatter<CurrencyFormatter>());
}

This sets up a mapping between the DomainModel and ViewModel and additionally applies a custom formatter for CurrencyProperty.  The formatter must implement the IValueFormatter interface like so:

public class CurrencyFormatter : IValueFormatter
{
    ///<summary>Formats source value as currency</summary>
    public string FormatValue(ResolutionContext context)
    {
        return string.Format(CultureInfo.CurrentCulture, "{0:c}", context.SourceValue);
    }
}

…and a simple conversion constructor on the ViewModel:

/// <summary> Creates the view model from the domain model.</summary>
public ViewModel(DomainModel domainModel)
{
    Mapper.Map(domainModel, this);
}

Now, neither the Controller or View need concern about any formatting and can stay focused on orchestrating and layout:

public ViewResult Index()
{
    var model = new DomainModel{CurrencyProperty = 19.95m};

    var viewModel = new ViewModel(model);

    return View(viewModel);
}
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel>" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using(Html.BeginForm()) {%>
    <%= Html.TextBoxFor(m=>m.CurrencyProperty)%>
<%} %>
</asp:Content>

Aside: TextBoxFor is an upcoming ASP.NET MVC 2 feature that’s available today in MVC Futures or the RC.  Check out Matt’s post for some neat stuff.

Mapping from View Model back to Domain Model

So now the formatted value is being rendered – but how do we go about the reverse trip back to the server?  First, to define an action:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(ViewModel viewModel)
{
    var model = new DomainModel();
    
    viewModel.MapTo(model);

    // ... return a view or action result
}

Aside: for validating that what the user enters is in the correct format, see another post about jQuery Validate here.

… and a Map method on the ViewModel:

public void MapTo(DomainModel domainModel)
{
    Mapper.Map(this, domainModel);
}

But this mapping will fail without first creating a definition back from the ViewModel to the Model.  In the ViewModel’s static constructor:

  // from vm to dm
  Mapper.CreateMap<ViewModel, DomainModel>()
   .ForMember(dm => dm.CurrencyProperty, 
    mc => mc
     .ResolveUsing<CurrencyResolver>()
     .FromMember(vm => vm.CurrencyProperty));

This utilizes another AutoMapper method - ResolveUsing - which can be used to get the string property back to a decimal.  The ValueResolver<TSource,TDestination> is defined like so:

public class CurrencyResolver : ValueResolver<string, decimal>
{
    ///<summary>Parses source value as currency</summary>
    protected override decimal ResolveCore(string source)
    {
        return decimal.Parse(source, NumberStyles.Currency, CultureInfo.CurrentCulture);
    }
}

Conclusions

There may be more elegant ways to accomplish formatting for MVC Views, but this method is quite workable.  In particular, I can imagine utilizing DataAnnotations’s DisplayFormatAttribute to decorate the Model or ViewModel and the framework automagically applying the formatting while rendering the View.

Monday, January 04, 2010 8:49:33 PM (Eastern Standard Time, UTC-05:00)  #   
Comments [3] -
# Sunday, January 03, 2010

When using Jeditable, there is no form element to bind jQuery Validate rules with.  Instead, when an editable element is clicked or activated, it dynamically creates a new form and input element and destroys them after the user is done editing.  For the ViewModel from Part 1, the View might be rendered like so for Jeditable:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ValidateViewModel>" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using(Html.BeginForm()) {%>
    <%= Html.ValidationSummary() %>
    <label for="StringRequired">StringRequired:</label>
    <div class="editable" id="StringRequired" name="StringRequired">
        <%= Model.StringRequired %>
    </div>
    
    <label for="DoubleRange13_100">DoulbeRange13_100:</label>
    <div class="editable" id="DoubleRange13_100" name="DoubleRange13_100">
        <%= Model.DoubleRange13_100%>
    </div>
<%} %>
</asp:Content>

xVal’s ClientSideValidation<TViewModel>() used in Part 1 won’t work to validate this.  The reason?  It generates a script that binds validation directly to the form elements on page load.  The rendered script looks for the ViewModel looks like:

<script type="text/javascript">
xVal.AttachValidator(null, 
    {"Fields":[
      {
         "FieldName":"StringRequired",
         "FieldRules":[
            {
               "RuleName":"Required",
               "RuleParameters":{

               },
               "Message":"This string is required"
            },
            {
               "FieldName":"DoubleRange13_100",
               "FieldRules":[
                  {
                     "RuleName":"Range",
                     "RuleParameters":{
                        "Min":"13",
                        "Max":"100",
                        "Type":"decimal"
                     },
                     "Message":"Must be between 13 and 100"
                  }
               ]
            }
         ]
      }
    ]}, {})
</script>

The rules are in the xVal’s StandardJSON format and the AttachValidator function (in xVal.jquery.validate.js) scans the DOM and attaches jQuery Validate rules as attributes to the matched input elements.  Since Jeditable doesn’t create these elements until they’re actively being edited, the rules have nothing to attach to since they don’t exist yet.  Fortunately, jQuery Validate provides several strategies for defining the rules.  In addition to being able to attach attributes to the input elements, the rules can be placed in a separate data structure.  jQuery Validate refers to these as “static rules”.  Instead of attaching the xVal rule set directly to the elements, it can be adapted to the static rule set that jQuery Validate can use directly.  The structure for the ViewModel rules will look like:

{
    rules: {
        StringRequired: {
            required: true
        },
        DoubleRange13_100: {
            number: true,
            range: ["13”, "100"]
        }
    }
    messages: {
        StringRequired: {
            required: "This string is required."
        },
        DoubleRange13_100: {
            range: "Must be between 13 and 100"
        }
    }
}

I've adapted some javascript to do this conversion - it's available here

.  To get the ViewModel’s rules into this format for javascript consumption, this line is added:
<script type="text/javascript">
    var validateOptions 
        = convertXvalToValidateOptions(
            <%= Html.ClientSideValidationRules<ValidateViewModel>()%>
        );
</script>

 

To get these attached to form elements as soon as the user activates them, Jeditable’s “plugin” feature is utilized:

$(function() { // <- on document ready
    // register plugin with Jeditable to tie in jQuery Validate
    $.editable.types['text'].plugin = bindValidate;
    
    // attach Jeditable to each element with class "editable"
    // Note: this must be done one-by-one so that the 
    // element's name can be assigned to Jeditable's "name" 
    // option which is used by jQuery Validate
    $('.editable').each(function() {
        var element = $(this);
        
        element.editable(
            'SaveUrlOrFunctionGoesHere',
            {
                // submit when the element is blurred
                onblur: 'submit',
                onsubmit: jeditableValidate,
                // assign the name of the input element 
                // from the element's name - this is needed 
                // because it's what jQuery Validate uses 
                // to bind the rules to the input element
                name: element.attr('name')
            }
        );
    });
});

// Jeditable plugin
function bindValidate(settings, self) {
    // attach jQuery Validate to 
    // Jeditable's dynamically created form
    $('form', self).validate(validateOptions);
}

// runs before values are submitted to server
function jeditableValidate(settings, self) {
    // validate the Jeditable dynamically created form
    return $('form', self).valid();
}

With this glue in place, the form elements will now be validated with the rules defined in the ViewModel.  All fields valid:

jQueryValidateJeditable1

…and here after both have invalid values:

jQueryValidateJeditable2

A few notes:

  • Any additional options to be sent to jQuery Validate can be attached to the validateOptions object. I’ve used this to place all error messages into a separate errorLabelContainer (like here).
  • I feel that AttachValidator function in xVal.jquery.validate.js from could become more loosely coupled by separating the rule conversion from the DOM element attachment.

I think both of these jQuery libraries provide a great benefit when creating interactive and helpful forms.  Kudos to Jörn Zaefferer and Mika Tuupola for the good work.  xVal is likewise an excellent library – thanks to Steve Sanderson.

Sunday, January 03, 2010 12:47:00 AM (Eastern Standard Time, UTC-05:00)  #   
Comments [0] -
Linkroll
Archive
<January 2012>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
James Kolpack
Sign In
All Content © 2012, James Kolpack
DasBlog theme 'Business' created by Christoph De Baene (delarou)
ASP .NET Web Hosting By Arvixe