Instructor: 00:01 Let's look at the optional fields. These are fields that the user can leave blank, but if some input is provided, then the field needs to be validated. The way we usually model optional things in Elm is by using the maybe type. In this case, if we want to make age optional, we could say that it's a field of a maybe int.
00:22 To have slightly more elegant and more readable model, we could create a type alias for this. Let me type type alias optional field of A. That will be the same as saying field of maybe of A. Here, I can write that age is an optional field of int.
00:50 Let's look at the validation now. Here with age, we're saying validate that the age is a natural number, but now, we want to change things so that an empty input is also considered a valid input. I want to define a function -- let me call this optional -- that takes a validator from string to A, and returns a validator from string to maybe A.
01:17 We will take a validator like this is natural, and it will return a softer validator, so to speak, that allows for an empty input. Let me call the first validator validate, then the input, S. This will the string input by the user.
01:34 I can just say that if S is empty, then we will return an OK with nothing. Nothing is a maybe that has no data. Else, we have run the validation. We'll validate S. This will return a result of A. What we want is a result of maybe of A. We need to do result.map just to put a result in value into a maybe.
02:05 The way you would use this is that here, you take the isNatural validator, and you pass it to optional. Let me fix this typo here. This is equals. Now I have a type error, because here, model.age is now a maybe of int. Let me change this here, maybe int. As a result, I also need to change the way in which age is encoded.
02:32 I will say age, and then I will say maybe.map encode.int. Then, maybe with default encode.null. If age contains an int, then we use encode.int, and otherwise, we use null.
02:54 Let me also change my view slightly. I'll put a star next to your email and your message, to give the user some signal that these are mandatory fields. With age, I remove the required true attributes. Let me test this. If I click submit, you can see that these two fields that are mandatory have been validated, but here, there are no validation errors.
03:16 However, there is a bit of a problem, in that, we get nothing printed out. That's because here, we're using toString on a validate now is a maybe. Let me improve this. Rather than using toString, we will say maybe.map toString, and then maybe with default empty string.
03:41 Let me click submit. Here, you can see that we still have the placeholder, this problem has been fixed. Now, if I say 22, then there's also no validation. You can see age is a valid 22. If I say, "Hello," then age is invalid, and we get the error label. Most importantly, if there's no input, then this is valid nothing as we intended.