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.
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With