Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Handling form submission
3.
Imports
4.
Form Basics
4.1.
Defining a form
4.2.
Defining constraints on the form
4.3.
Defining ad-hoc conditions 
4.4.
Validating a form in an Action 
4.5.
Displaying forms in a template view 
5.
Protecting against Cross-Site Request Forgery
5.1.
Trusting CORS requests
6.
Making Use Of Custom Validations 
7.
Custom Field Constructors
8.
Frequently Asked Questions
8.1.
Why is Scala so well paid? 
8.2.
Is Scala a good career choice? 
8.3.
Does Scala outperform Java? 
8.4.
What do developers do in Scala? 
8.5.
What is form validation?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Scala Developers-Form Submission and Validation

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Scala is a computer language for creating robust static systems and functional programs. It is JVM-based and object-oriented. It is capable of interacting with libraries and existing Java programs. The idea of primitive data is absent. Thus it is widely believed to be a static type of language.

Handling form submission

Every online application has to handle and submit forms. Play includes capabilities that allow managing both simple and complicated forms, simple and possible.

Form Validation & Form Submission

The idea of binding data serves as the foundation for Play's form handling strategy. Play will look for formatted values and attach them to a Form object when data from a POST request arrives. Play may utilize the bound form to run custom validations, value a case class with data, and other things.

Forms are typically utilized straight from a BaseController instance. Form definitions are solely for handling input. Hence it is fair to use a different Form for each separate POST. However, they do not necessarily need to correspond exactly with case classes or models.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Imports

Import the necessary packages into your class in order to use forms:

import play.api.data.
import play.api.data.Forms.


Into your class, import the necessary libraries to use validation and constraints:

import play.api.data.validation.Constraints.

Form Basics

Form Basics

Defining a form

Create a case class first, and then add the components. Here, we want to record a user's name and age, so we build an object called UserData.

case class UserData(fname: String, currentage: Int).

 

After creating a case class, the next thing to do is create a Form structure. A "Form" converts form data into a bound instance of a case class.

val userForm = Form(
  mapping(
    "fname" -> text,
    "currentage"  -> number
  )(UserData.apply)(UserData.unapply)
)

 

The Forms object specifies the mapping strategy. The apply function and unapply function are also passed to this method, along with the form's names and restrictions. UserData is a case class. Thus we can directly incorporate its apply and unapply methods into the mapping function.

Defining constraints on the form

Of Empty strings is accepted by the text constraint as legitimate. This implies that name may be empty in this situation without causing a problem, which is not what we want. Using the non-empty text constraint can guarantee that name has the correct value.

If the form's input does not adhere to the limitations, using it will result in a form with problems.

The Forms object has the following declared default constraints: 

Forms object

Defining ad-hoc conditions
 

  • Using the validation package, you can specify your ad hoc constraints on the case classes.
     
  • Additionally, you can specify ad hoc restrictions on the case classes.
     
  • Additionally, you have the choice of creating your custom validations. For more information, please refer to the section on custom validations.

Validating a form in an Action
 

  • We can validate the form inside an action and process the form with errors now that we have limitations. 
     
  • The fold method, which accepts two functions and calls the first function if the binding fails and the second if it succeeds, is used to do this.

Displaying forms in a template view 

Once a form has been created, it must be made available to the template engine. Add the argument "form" to the view template to accomplish this. The header at the top of the page for user.scala.html will appear as follows: 

@ (userForm: Form[UserData]) (Illustrative: Messages) 

 

When rendering user.scala.html, you should initially pass the empty user form since user.scala.html requires a form to be passed in:

There are various input aids. However, the following are the most beneficial:

input aids

Protecting against Cross-Site Request Forgery


A security flaw known as cross-site request forgery (CSRF) allows an attacker to mislead a victim's browser into sending a request while the victim is still logged in to the site. Since the session token is provided with every request, an attacker can initiate requests on behalf of the victim if they can force the browser to do so. 

It is advised that you become familiar with CSRF, the types of attack vectors, and what attack vectors are not. Starting with this OWASP material is what we advise. 

The lack of a clear specification regarding what is acceptable from plugins and potential extensions to standards makes it difficult to determine what requests are secure and what are susceptible to CSRF requests. The responsibility for fixing CSRF vulnerabilities has historically fallen on the frameworks because browser plugins and extensions have loosened the restrictions that frameworks had previously believed could be trusted. Play adopts a conservative stance, but you can set the precise timing of when a check is performed. When each of the following conditions holds true, Play will, by default, demand a CSRF check:

Cross-Site Request Forgery

Play’s CSRF protection

Play offers several ways to check whether a request isn't a CSRF request. The key component is a CSRF token. Every time a form is submitted, this token is added to the query string or form body and the user's session. Then, play checks to see if both tokens are present and identical.

Trusting CORS requests

The CSRF filter will automatically permit CORS requests from trusted origins if a CORS filter is present before it. Set the configuration option to disable this check. play.filters.csrf.bypassCorsTrustedOrigins is set to false.

Making Use Of Custom Validations 

Using the verifying approach, you can set ad hoc constraints with the validation package. Play does, however, allow you to design your unique constraints using the Constraint case class. 

Here, we'll use regular expressions to construct a straightforward constraint on password strength that verifies the password does not contain only letters or only digits. We utilize a constraint that accepts a function that returns a ValidationResult to return the outcomes of the password check:

val allNumbers = """\d*""".r
val allLetters = """[A-Za-z]*""".r

val passwordCheckConstraint: Constraint[String] = Constraint("constraints.passwordcheck")({ plainText =>
  val errors = plainText match {
    case allNumbers() => Seq(ValidationError(" All numbers is Password"))
    case allLetters() => Seq(ValidationError("All letters is Password"))
    case _            => Nil
  }
  if (errors.isEmpty) {
    Valid
  } else {
    Invalid(errors)
  }
})

Custom Field Constructors

In addition to the input> tag, a field rendering also requires a label> tag and perhaps other tags that your CSS framework uses to embellish the field. 

All input helpers include a FieldConstructor that handles this portion by default. The default one creates HTML in the following format when there are no other field builders available in the scope:

<dl class="error" id="username_field">
    <dt><label for="username">Unique Username:</label></dt>
    <dd><input type="text" name="username" id="username" value=""></dd>
    <dd class="error">Required field</dd>
    <dd class="error">Error</dd>
    <dd class="info">It is also Required</dd>
    <dd class="info">Constraint</dd>
</dl>

Frequently Asked Questions

Why is Scala so well paid? 

"Scala and Go are regarded as emerging abilities, which have seen a significant increase in demand over the previous five years. Additionally, they are powerful in [Science, Technology, Engineering, and Math] STEM skills, a sign that STEM occupations are in high demand and pay well."

Is Scala a good career choice? 

One of the greatest languages to learn today before big data and data science is Scala. Scala's ability to do this aids in its continued viability in the IT sector. The emerging fields of big data and data science have high technical expert demand.

Does Scala outperform Java? 

According to the study, Scala is quicker than Java and Go when typical developers write code without too much thought given to optimization. The study took advantage of each language's standard, idiomatic data structures.

What do developers do in Scala? 

An expert in developing, building, and maintaining Scala-based applications is known as a "Scala developer." Additionally, they perform software analysis, write code in accordance with app specifications, and work together with the software development team to validate the application designs.

What is form validation?

A web form's validation is a "technical procedure where it is checked to see if the data entered by the user is accurate." Either the form will notify the user that they made a mistake and must correct it before continuing, or the form will be verified, and the user will be able to finish the registration process.

Conclusion

In this article, we have gone through an understanding of Handling form submission with form basics and validation. And also cover Protecting against Cross-Site Request Forgery and Making Use Of Custom Validations.

I suppose it is clear to you. Still have doubt? Then please comment.

Are you eager to read more articles on Routes in Scala? Coding Ninjas cover you, so don't worry. View more topics on Coding ninjas.

Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

If you find any problems, please comment. We will love to answer your questions.

Attempt our Online Mock Test Series on Coding Ninjas Studio now

Ninja, have a great time learning.

Previous article
Scala Developers - The Twirl Template Engine
Next article
Scala developers-Working with JSON
Live masterclass