Trim each input field except for NoTrim attributes

I am working on an ASP.NET MVC 2 application that I have not created. All input fields in the application are trimmed during model binding. However, I want to have a NoTrim attribute that prevents cropping of certain fields.

For example, I have the following status dropdown box:

<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 the user selects "International", I get a validation error because two spaces are truncated, and State is a required field.

Here is what I would like to do:

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

Here is what I have for the attribute:

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

Application_Start creates a custom mediation device:

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

Here is the part of the bunch that performs 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 ); } 
+7
source share
3 answers

NoTrim looks good, but it is a [Required] attribute that will reject spaces.

The RequiredAttribute attribute indicates that when a field in a form is validated, the field must contain a value. Validation exception if the property is null, contains an empty string ("") or contains only space characters.

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

To work around this problem, you can create your own version of the attribute or use the RegexAttribute attribute. I'm not sure if the AllowEmptyStrings property will work.

+2
source

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

0
source

how about this?

 [MinLength(2, ErrorMessage = "State is required")] [DisplayFormat(ConvertEmptyStringToNull=false)] 
0
source

All Articles