media-io / yaserde

Yet Another Serializer/Deserializer
MIT License
175 stars 57 forks source link

Input validation #116

Open azzamsa opened 3 years ago

azzamsa commented 3 years ago

Is there a way to validate XML string input?

use yaserde_derive::YaDeserialize;

#[derive(Debug, YaDeserialize)]
pub struct Person {
    name: String,
    age: i32,
}

fn main() {
    let input = "<Person><name></name><age>20</age></Person>";
    let person: Person = yaserde::de::from_str(input).unwrap();
    println!("Person: {:?}", person);
}

Given the code above, is there a way for me to do some validation such:

impl Person {
    pub fn new(name: String, age: i32) -> Result<Self, ()> {
        if name == "" {
            return Err(());
        }
        Ok(Person { name, age })
    }
}

or

#[derive(Debug, YaDeserialize)]
pub struct Person {
    #[validate(length(min = 1))]
    name: String,
    age: i32,
}

So when processing the data, I can make sure that the input are validated. Maybe something like https://github.com/Keats/validator/issues/162 but for XML.