Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maximum length of separated word of string property C# EF

Here is part of my model

public class Sensor
{
    public int Id { get; set; }

    [Required]
    [MaxLength(40)]
    public string Name { get; set; }
}

Name is some text filed who is have maximum length of 40 symbols. And in this text field is possible to have few words.

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

For Example is have: "Motion Detector". And I want the word to be maximum 8 symbols. This mean Motion and Detector is need to be less of 8 symbols length. The user can't write like "MotionDetector" whose length is 12 symbols.

like image 328
evelikov92 Avatar asked Mar 01 '16 05:03

evelikov92


2 Answers

One way is you can use the setter in the property to control the max length per word:

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
  }
}
like image 74
Ian Avatar answered Oct 16 '22 17:10

Ian


Ideally, you should have a clear separation between data models (generated by EF) and view models (used for binding). So, your should validating user data against view model definition, not data model definition.

In MVC, MaxLength attribute is not meant to validation maximum allowed input, StringLength is a validation attribute, as explanained 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 is used, SensorViewModel will be your @model.

To easily transfer data between Sensor and SensorViewModel an automapping library can be used. E.g. AutoMapper.

If you are not using MVC, there are alternative for WPF and Windows Forms. Shortly put, you can avoid the boilerplate code of simple validation by using attributes.

like image 3
Alexei - check Codidact Avatar answered Oct 16 '22 18:10

Alexei - check Codidact