Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Customize Validation Error Messages in Elm

    Enrico BuonannoEnrico Buonanno

    In this lesson, we'll refactor our code by making our validation functions more general by enabling a custom error message. No more hardcoded error messages!



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:01 let's look at the error messages in application. You can see that the messages are not very nice. This starts with lower case. This starts with upper case.

    00:11 What if I wanted this mandatory field message to be more specific? For example, an email is required. What if I wanted this to be more user-friendly? What if I have a site that involves localization? I have to translate the message depending on the language.

    00:30 The problem is that at the moment our messages are hard-coded in our validation functions. As a rule in functional programming, to make things more general, you add parameters.

    00:40 For example, it's not empty could take a string as the error message to use. Let's call it error. Then, we'll use this error in the arrow case. We'll do the same for the other validation functions. Here, we're using string to int. We'll say result map error with error.

    01:07 Actually, map error expects a function. Let me use always err. I also need to add error as a parameter here. Let me refactor the remaining functions.

    01:36 To make the signature a bit more meaningful still, I could create a type alias error message for string and use this in my signatures to make them even more intention revealing.

    01:53 Now, I have no more hard-coded error messages in my validation logic. The next step is to fix the quote where I perform invalidation. Let me extract a few variables here. I don't need these parentheses.

    02:14 But I do need to provide the error as an argument. I will say, "An email is required." I will chain that with the following validation with the message, "Please ensure this is a valid email." Now, let me put the valid edit field email in the variable, as well.

    02:51 Let me do a similar refactoring for the other fields.

    03:27 Now, let me see what happens. When I submit, we get the custom message, "An email is required," "A message is required." Let me enter some other data. Again, we see the new messages being displayed...