Displaying a custom validation error - "data"

Hi,

I’ve tried to create a custom validation like the chapter 21 of the book.

This is my code:
extension RegisterData: Validatable, Reflectable {
static func validations() throws → Validations {
var validations = Validations(RegisterData.self)
try validations.add(.name, .ascii)
try validations.add(.username, .alphanumeric && .count(3…))
try validations.add(.password, .count(8…))
validations.add(“passwords match”) { model in
guard model.password == model.confirmPassword else {
throw BasicValidationError(“Las contraseñas no coinciden”)
}
}
return validations
}
}

When I introduce two different passwords, the message on the screen is:
“data Las contraseñas no coinciden”, when it should be only “Las contraseñas no coinciden”.

How can I delete the “data” from the message?

Thanks!

How are you showing the message on the screen?

I’m showing the message like this:

#if(mensaje) {
<div id="alerta" class="alert alert-danger">
    Revisa los siguientes errores: </br>
    #(mensaje)
</div>
}

How are you setting up the context to send to the Leaf template?

I’ve got the same issue. FYI - I’m passing the error message(s) back as part of the URL, similar to the way the registerPostHandler does. Will keep digging!

Update! I went back and entered mismatched passwords on the register screen. The word “data” shows up in front of the “passwords don’t match” message. I don’t remember seeing that when I first did that part of the tutorial, but it has been a while. Strange. :thinking:

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

Not strange, working as designed!

BasicValidationError combines a path (the field that caused the error) and a message (readable description of the error). The returned error message includes the path and the message. If no path is specified, the word “data” is used.

I came up with the following definition for a validation error that doesn’t use a path. This is handy for when you have to use multiple fields together to determine if things are ok.

/// A validation error that does not use dynamic key paths.
/// Only the associated message will be displayed.

import Validation

public struct NoPathValidationError: ValidationError {
  public var path: [String] = []
  public var identifier: String = "NoPathValidationError"
  
  public var reason: String {
    return message
  }

  // Error message
  public var message: String
  
  // Create a new error
  public init(_ message: String) {
    self.message = message
  }
}

Using @frasco’s example, if you change
throw BasicValidationError(“Las contraseñas no coinciden”)
to
throw NoPathValidationError(“Las contraseñas no coinciden”)
you should get your desired results.

If anybody has any suggestions on a better way to do this, let me know!

Have fun!

1 Like

@rcasey Thank you for sharing your solution - much appreciated! :]

1 Like