Search code examples
formsvalidationscalalift

validation of fields in a form in scala with lift frame work


I am working with the Lift framework and Scala. I have a form to sign up to my application, and I want to validate all the fields in it. I have a snippet where I access my form values, and one validation class where I wrote my validation functions. The following code is what I've tried so far. In my Snippet:

if(validationClassObject.validateName(first_name)){
  if(validationClassObject.validateName(last_name)){
    if(validationClassObject.validateEmail(email)){
      if(validationClassObject.validateUserName(name)){

        // Adding values to the DB
        S.redirectTo("/")

      }
      else{
        S.notice("Invalid User Name")
      }               
    }
    else{
      S.notice("Invalid Mail Id")                 
    }
  }
  else{
    S.notice("Invalid Last name")
  }           
}
else{
  S.notice("Invalid First Name")
}

In the validationClass I wrote the validation code looks like:

//function for validating mail address
 def validateEmail(email: String): Boolean =
     """(\w+)@([\w\.]+)""".r.unapplySeq(email).isDefined
 //code for validating remaining fileds like above

This is working, but I know this is not the best way of coding this operation in Scala. How could I modify my code in a more scalable way? How can I use case classes here?


Solution

  • You could do:

      def av[T,V](validationFunction: => Boolean, error: => T)(f: => V)={
        if(!validationFunction) error
         else f
      }
      def v[V](validationFunction: => Boolean, error: => String)(f: => V)=av(validationFunction,S.notice(error))(f)
    
    
      import validationCalssObject._
    
      v(validateName(last_name),"Invalid Last name"){v(validateName(name),"Invalid User Name"){...}}
    

    av is a abstract method with T and V as result types for the error function and continue function f. v is the more specific function what expects a string for error and encapsulates the notice() call. we give f as the part in the curly braces v(validation, errormsg){/*todo when there is no problem*/}.