lumeohq / xsd-parser-rs

A xsd/wsdl => rust code generator written in rust
Apache License 2.0
97 stars 34 forks source link

Add validation based on restriction #8

Closed LeonidKrutovsky closed 4 years ago

LeonidKrutovsky commented 4 years ago
<xs:simpleType name="Name">
  <xs:restriction base="xs:string">
    <xs:maxLength value="64"/>
  </xs:restriction>
</xs:simpleType>
victor-soloviev commented 4 years ago

For this structure we could generate following code (using https://github.com/Keats/validator):

#[derive(Default, PartialEq, Debug)]
pub struct Name (String);

impl Validate for Name {
    fn validate(&self) -> Result<(), ValidationErrors> {
        if self.0.len() > 64 {
            let mut errors = ValidationErrors::new();
            errors.add("Wrong name length", ValidationError::new("Name is too long"));
            return Err(errors);
        }
        Ok(())
    }
}

Code above could be tested with this:

let mut name: Name = Default::default();
    name.0 = "...".to_string();
    match name.validate() {
        Ok(_) => println!("ok"),
        Err(e) => println!("{}", e)
    };

Note that

We could create a macros that generates impl Validate for us. We want something like that:

#[derive(Default, PartialEq, Debug, Validate)]
#[ValidateLengthMax = 64]
pub struct Name (String);