package htmlx
import (
"encoding/xml"
"fmt"
)
type Input struct {
Label string
Type string `json:",omitempty"`
Name string
Required bool `json:",omitempty"`
Value string
MinLength uint `json:",omitempty"`
Error string `json:",omitempty"`
}
func (i Input) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
start.Name = xml.Name{Local: "Input"}
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "Label"}, Value: i.Label})
if i.Type != "" {
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "Type"}, Value: i.Type})
}
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "Name"}, Value: i.Name})
if i.Required {
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "Required"}, Value: "true"})
}
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "Value"}, Value: i.Value})
if i.MinLength > 0 {
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "MinLength"}, Value: fmt.Sprintf("%d", i.MinLength)})
}
if err := e.EncodeToken(start); err != nil {
return nil
}
if i.Error != "" {
errorStart := xml.StartElement{Name: xml.Name{Local: "Error"}}
if err := e.EncodeElement(i.Error, errorStart); err != nil {
return err
}
}
if err := e.EncodeToken(start.End()); err != nil {
return err
}
return nil
}
func (p *Input) Validate() bool {
if p.Required && p.Value == "" {
p.Error = fmt.Sprintf("%v is required", p.Name)
return false
}
value_len := len(p.Value)
if p.MinLength > 0 && int(p.MinLength) > value_len {
p.Error = fmt.Sprintf("%v requires at least %v characters (currently %v characters)", p.Name, p.MinLength, value_len)
return false
}
return true
}