Backstory on Validate

10/07/2018 22:34 BST

While I was in progress of creating the admin panel for this site, I needed something I can rely on for form validation, I did try to have a look at other solutions online, I honestly did not find them suitable for my needs. So I decided to write my own solution.

All it’s is really is just a raw value validator, I find that it’s works quite well even for the most quirkiest of form or even an array of multiple form. On this site each blog post has multiple component, each of them have their own validation rules and each component has a hash and it’s suffix to the form field, so it’s does not conflict with the other component.

I felt that the other validation system in Goland would not of cope with that, I needed a system that only takes one value at a time, but not the entire map (or the request) at once that overkill to me and here an example of my system.

All I did was call the validate function and pass the raw value in, than the validation rule to validate the value against, it’s quite simple really. Verbosity does not really bother me too much, I work with a reliable IDE, it’s make my life easier when it’s comes to working with verbose code.

Because I use hash and suffix, there is no way I can use and cache a system like govalidator, I can use the system but I can’t cache the rules because it’s requires the form field name which happens to have a hash suffix, with my system I kept the field name and the validation rules decoupled, so therefore I was able to cache the rules, as you can see from the example below

func NewFormBuilderValidator() FormBuilderValidator {
	return FormBuilderValidator{
		nameRules:  []vString.ValidationRule{vString.Mandatory(), vString.BetweenRune(5, 50)},
		emailRules: []vString.ValidationRule{vString.Mandatory(), vString.Email()},
		ageRules:   []vInt.ValidationRule{vInt.Mandatory(), vInt.Min(21)},
	}
}

func (v FormBuilderValidator) NewValidatedForm(params url.Values) Form {
	f := newForm()
	f.Checked = true

	f.Name, f.NameErr = vString.Validate(params.Get("name"), v.nameRules...)
	f.Email, f.EmailErr = vString.Validate(params.Get("email"), v.emailRules...)
	f.EmailConfirm, f.EmailConfirmErr = vString.Validate(params.Get("email-confirm"), append(v.emailRules,
		vString.MustMatch(f.Email, "Email"))...)
	f.Age, f.AgeErr = vInt.ValidateFromString(params.Get("age"), v.ageRules...)

	f.Valid = vError.CheckErr(f.NameErr, f.EmailErr, f.EmailConfirmErr, f.AgeErr)
	return *f
}

No matter how dynamic the field name is, I will have no problem caching the validation rules.

| |