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...






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


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế