How to set max length of split word of string property C # EF

Here is a part of my model

public class Sensor { public int Id { get; set; } [Required] [MaxLength(40)] public string Name { get; set; } } 

A name is some text that has a maximum length of 40 characters. And in this text box it is possible to have a few words.

My question is, is it possible to set the maximum word length in the Name property?

For example, there is: "Motion Detector". And I want the word to be a maximum of 8 characters. This means that the motion and detector must be less than 8 characters. The user cannot write as "MotionDetector", whose length is 12 characters.

+6
source share
2 answers

In one way, you can use setter in a property to control the maximum word length:

 set { string[] words = value.Split(' ') if (words.Any(x => x.Length > 8)){ //error, do something } else { //OK, pass Name = value; //only update Name if the length for all words are valid } } 
+4
source

Ideally, you should have a clear separation between data models (generated by EF) and view models (used for binding). Therefore, you should check the user data against the definition of the presentation model, and not the definition of the data model.

In MVC the MaxLength attribute is not intended to confirm the maximum allowable input; StringLength is a validation attribute, as described here .

In your particular case:

 // this is the data model public class Sensor { public int Id { get; set; } [Required] [MaxLength(40)] public string Name { get; set; } } // this is the data model public class SensorViewModel { public int Id { get; set; } [Required] [StringLength(8)] public string Name { get; set; } } 

If MVC used, SensorViewModel will be your @model .

To easily transfer data between Sensor and SensorViewModel , you can use the auto-tuning library. For instance. AutoMapper

If you are not using MVC , there is an alternative to WPF and Windows Forms . In short, you can avoid the code of a simple validation template using attributes.

+3
source

All Articles