Created
September 25, 2017 02:16
-
-
Save LSTANCZYK/9bb27679e5c4898263c566e67ce82d57 to your computer and use it in GitHub Desktop.
Data annotation attribute to verify that string is a valid XML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel.DataAnnotations; | |
using System.Xml; | |
namespace CHR.API.Provisioning.ATT.BusinessLogic.DataValidation | |
{ | |
/// <inheritdoc /> | |
/// <summary> | |
/// Data annotation attribute to verify that string is a valid XML | |
/// </summary> | |
public class ValidXml : ValidationAttribute | |
{ | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
if (!(value is string)) | |
{ | |
return new ValidationResult($"'{validationContext.MemberName}' property of '{validationContext.ObjectType.Name}' class is not a string property."); | |
} | |
var xmlString = (string) value; | |
try | |
{ | |
// Check we actually have a value | |
if (string.IsNullOrEmpty(xmlString) == false) | |
{ | |
// Try to load the value into a document | |
var xmlDoc = new XmlDocument(); | |
xmlDoc.LoadXml(xmlString); | |
// If we managed with no exception then this is valid XML! | |
return ValidationResult.Success; | |
} | |
// A blank value is not valid xml | |
return new ValidationResult($"'{validationContext.MemberName}' is an empty string."); | |
} | |
catch (XmlException) | |
{ | |
return new ValidationResult($"'{validationContext.MemberName}' is not a valid XML."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment