0

Hi I'm new in C# and I have created a WPF form that takes in a csv and save it in the db. Now I was wondering if there are a Validation Library that I can use to make those field checking easier? Like I would like to implement a field required or something and it will throw an error if the field is not required. How can I achieve this? I have read some code that has something like this

[Required] // Not sure if this is the correct format
public string Name()
{
  get;set;
}

So basically I was thinking of a middleware type of validation where I just place the [Required] attribute in the model class and it will do the validation for me. Is there such a thing?

Update: What I mean by validating is that when after I select a csv file, it will read through per row/column now each column will be validated like ex. For column[0] (assuming this is field for Name) then when this field is read and assign to a variable it should be validated before proceeding in assigning to a variable. Not sure if this is possible more it's something like this

string[] content = row.Split('|');
Customer customer = new Customer(content);
Lis<KeyValuePair<string, string>> rowList = Converter.ToKeyValuePair(customer);

And here's the code for the Customer class

class Converter
{
    public static List<KeyValuePair<string,string>> ToKeyValuePair(Customer customer)
    {
         List<KeyValuePair<string, string>> rowList = new List<keyValuePari<string, string>>();
         rowList.Add(new KeyValuePair<string, string>('name', customer.Name));
    }

    return rowList;
}

// Class Customer

class Customer
{
    private string _name;

    public Customer(string[] content)
    {
        this.Name = content[0];
    }

    [Required] // Maybe some auto validation here where when the property is accessed it should be validated immediately
    public string Name
    {
         get { return _name; }
         set {
             // I'm thinking of some validation here?
              _name = value;
         }
    }
}

As you can see in my example I wanted that whenever the property like this.Name = content[0] is accessed it automatically validate if the content has value or not

MadzQuestioning
  • 3,341
  • 8
  • 45
  • 76
  • Do you mean validating the model in the WPF form? Like disabling a 'Save' or 'Submit' button until the input is valid? – Ivan Vargas Aug 23 '20 at 22:52
  • @IvanVargas will update my question – MadzQuestioning Aug 24 '20 at 05:24
  • [This](https://stackoverflow.com/questions/17138749/how-to-manually-validate-a-model-with-attributes) might help you – Ivan Vargas Aug 24 '20 at 07:12
  • @IvanVargas, That is for web(asp.net). WPF is desktop platform. – Mat J Aug 24 '20 at 10:08
  • @MadzQuestioning, In wpf, you should use [IDataErrorInfo](https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-validation-logic-on-custom-objects) interface on your model/viewmodel instead of attributes. – Mat J Aug 24 '20 at 10:10

1 Answers1

0

There is no built-in "validation library" as such. You should implement the INotifyDataErrorInfo interface in your class:

public class Model
{
    [Required(ErrorMessage = "You must enter a username.")]
    [StringLength(10, MinimumLength = 4,
        ErrorMessage = "The username must be between 4 and 10 characters long")]
    [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "The username must only contain letters (a-z, A-Z).")]
    public string Username { get; set; }

    [Required(ErrorMessage = "You must enter a name.")]
    public string Name { get; set; }
}

public class ViewModel : INotifyDataErrorInfo
{
    private readonly Dictionary<string, ICollection<string>>
       _validationErrors = new Dictionary<string, ICollection<string>>();
    private readonly Model _user = new Model();

    public string Username
    {
        get { return _user.Username; }
        set
        {
            _user.Username = value;
            ValidateModelProperty(value, "Username");
        }
    }

    public string Name
    {
        get { return _user.Name; }
        set
        {
            _user.Name = value;
            ValidateModelProperty(value, "Name");
        }
    }

    protected void ValidateModelProperty(object value, string propertyName)
    {
        if (_validationErrors.ContainsKey(propertyName))
            _validationErrors.Remove(propertyName);

        ICollection<ValidationResult> validationResults = new List<ValidationResult>();
        ValidationContext validationContext =
            new ValidationContext(_user, null, null) { MemberName = propertyName };
        if (!Validator.TryValidateProperty(value, validationContext, validationResults))
        {
            _validationErrors.Add(propertyName, new List<string>());
            foreach (ValidationResult validationResult in validationResults)
            {
                _validationErrors[propertyName].Add(validationResult.ErrorMessage);
            }
        }
        RaiseErrorsChanged(propertyName);
    }
    ...
}

The full data validation procedure in WPF, including examples of how to implement this interface and validate data using data annotations, is described in this blog post. Please read it through and feel free to ask another question if you run into a more specific issue.

mm8
  • 163,881
  • 10
  • 57
  • 88