Check data correctness before export to xml in C#
Check data correctness before export to xml in C#
I have class like that:
public class Animal
[Required]
[StringLength(20)]
public string Name get; set;
public double Weight get; set;
public double Height get; set;
public int AnimalID get; set;
and I have to generate XML using this, but before it, I have to check correctness of this data (e.g. Weight
cannot be longer than 100, AnimalID
should be in range 0 to 9).
Weight
AnimalID
How should I do this?
I have blackout...
if
I would write a Validator using fluentvalidation
– ChristianMurschall
Sep 9 '18 at 20:07
@GrantWinney yes, I can use everything.
– blue rabbit
Sep 9 '18 at 20:14
1 Answer
1
You can use DataAnnotations from DataAnnotations namespace. This way you can wrap the object in try/catch block like below and catch
ValidationExceptions:
try
Animal animal = GetAnimal();
catch(ValidationException ex)
public class Animal
[Required]
[StringLength(20)]
public string Name get; set;
[Required, RangeAttribute(0,100)]
public double Weight get; set;
public double Height get; set;
[Required, RangeAttribute(0, 9)]
public int AnimalID get; set;
Also, if you are using MVC then you can use methods like ModelState.IsValid etc.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not sure what you mean. Do you already know how to export it to XML? If so, can you include whatever code you've got so far? Testing the values is just some
if
blocks...– Grant
Sep 9 '18 at 20:04