Trim every input field except those with NoTrim attribute
Asked Answered
S

3

8

I am working on an ASP.NET MVC 2 application that I didn't create. All input fields in the application are trimmed during model binding. However, I want to have a NoTrim attribute that prevents certain fields from being trimmed.

For instance, I have the following state drop-down field:

<select name="State">
    <option value="">Select one...</option>
    <option value="  ">International</option>
    <option value="AA">Armed Forces Central/SA</option>
    <option value="AE">Armed Forces Europe</option>
    <option value="AK">Alaska</option>
    <option value="AL">Alabama</option>
    ...

The problem is that when a user chooses "International", I get a validation error because the two spaces are trimmed and State is a required field.

Here's what I'd like to be able to do:

    [Required( ErrorMessage = "State is required" )]
    [NoTrim]
    public string State { get; set; }

Here's what I've got for the attribute so far:

[AttributeUsage( AttributeTargets.Property, AllowMultiple = false )]
public sealed class NoTrimAttribute : Attribute
{
}

There is a custom model binder that gets set up in Application_Start:

protected void Application_Start()
{
    ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    ...

Here is the part of the model binder that does the trimming:

protected override void SetProperty( ControllerContext controllerContext,
                                     ModelBindingContext bindingContext,
                                     PropertyDescriptor propertyDescriptor,
                                     object value )
{
    if (propertyDescriptor.PropertyType == typeof( String ) && !propertyDescriptor.Attributes.OfType<NoTrimAttribute>().Any() )
    {
        var stringValue = (string)value;

        if (!string.IsNullOrEmpty( stringValue ))
        {
            value = stringValue.Trim();
        }
    }

    base.SetProperty( controllerContext, bindingContext, propertyDescriptor, value );
}
Sweettalk answered 11/7, 2012 at 21:14 Comment(3)
@KyleTrauberman, unfortunately I have no control over that aspect. It has to be whitespace. It's not trimmed by the browser but in the application somewhere.Sweettalk
Accidently deleted my comment: I asked who was doing the trimming and if something else could be used in place of whitespace.Gameto
Does this app have code to trim, or is MVC doing the trimming before binding to the model?Gameto
H
2

NoTrim looks good but it's that [Required] attribute that will reject whitespace.

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx

To workaround the issue, you could create your own version of the attribute or use a RegexAttribute. I'm not sure the AllowEmptyStrings property would work.

Histrionics answered 11/7, 2012 at 21:43 Comment(2)
That's it. Ended up creating a custom NoteNull attribute that allows whitespace.Sweettalk
Require attribute may reject a whitespace, but f.e. when entering names, initials an additional space may be unwanted, so the proposed solution is a great one.Discriminator
P
0

I would just replace the " " with something like "-1" or "-". If this is the only case, of course...

Pyrrhic answered 11/7, 2012 at 22:33 Comment(1)
This is not an option as the data is out of my hands.Sweettalk
P
0

how about this?

[MinLength(2, ErrorMessage = "State is required")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
Phonics answered 23/7, 2013 at 17:57 Comment(1)
Use [StringLength(2, ErrorMessage = "State is required")] instead for unobtrusive validations.Nubile

© 2022 - 2024 — McMap. All rights reserved.