10

I found all value passed by Model is not trimmed in ASP.net MVC3

Is there a way to:

  1. Apply a trim() on every field in Model (all string fields, at least; but all form fields are string before processed by Model, so better trim them all)
  2. Must before ModelState.IsValid() (because I often found code stucked at weird ModelState.IsValid and later found because the form item did not be trimmed.)

Thanks.

Eric Yin
  • 8,737
  • 19
  • 77
  • 118
  • 5
    See solution on http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo – Frank Sebastià Jun 22 '16 at 05:42

2 Answers2

12

You'll have to create a custom model binder to trim any model property that is a string.

References:
Custom model binding using IModelBinder in ASP.NET MVC
Iterating on an ASP.NET MVC Model Binder
6 Tips for ASP.NET MVC Model Binding
A Better Model Binder

Basically, you can take one of two approaches:

  1. Implement the IModelBinder interface
  2. Subclass the DefaultModelBinder class

Example

public class StringTrimmingBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // trim your string here and act accordingly

        // in the case the model property isn't a string
        return base.BindModel(controllerContext, bindingContext);
    }
}
Sevle
  • 3,109
  • 2
  • 19
  • 31
  • Sure, I will go search what is "custom model binder" now. Thanks for the hint – Eric Yin Feb 10 '12 at 03:45
  • Thanks for the link, reading.... – Eric Yin Feb 10 '12 at 03:49
  • Hi Mr Shark, could you please give me some working code, I do not really understand after read. I can do the trim part myself, but how to bind my code to a model, I do not have a clue. I don't even know where to put the code. – Eric Yin Feb 10 '12 at 03:53
  • 5
    To everyone after me: remember put this in `Global.asax` `Application_Start()` `ModelBinders.Binders.DefaultBinder = new whatsoeverbinder();` – Eric Yin Feb 10 '12 at 04:26
1

Just FYI, I also wrote a small JQuery Plug_in for my project to use trim(), startsWith() & endsWith() for all the inputs string from client side.

(function ($) {

    String.prototype.trim = function ()
    { return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) };

    String.prototype.startsWith = function (str)
    { return (this.match("^" + str) == str) };

    String.prototype.endsWith = function (str)
    { return (this.match(str + "$") == str) };     

})(jQuery);
Allen Wang
  • 978
  • 8
  • 12