What is the best Java email address validation method?¶
As usual, our example domain is order registration. Here is a request that we should validate:
{
"guest":{
"email":"vasya@belov.com"
}
}
If everything’s successful, I want to have a bag of data with methods corresponding to blocks and fields in json request, like that:
Result<OrderRegistrationRequestData> result = new ValidatedOrderRegistrationRequest(jsonRequest).result();
result.isSuccessful(); // true
result.value().raw().guest().email(); // vasya@belov.com
In a course of a validation process, I want to make sure that guest
is a valid json object.
That’s how the whole thing looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | public class ValidatedOrderRegistrationRequest implements Validatable<OrderRegistrationRequestData>
{
// ctor and jsonRequestString private property declaration
@Override
public Result<OrderRegistrationRequestData> result() throws Exception
{
return
new FastFail<>(
new WellFormedJson(
new Unnamed<>(Either.right(new Present<>(this.jsonRequestString)))
),
requestJsonObject ->
new UnnamedBlocOfNameds<>(
List.of(
new FastFail<>(
new IsJsonObject(
new Required(
new IndexedValue("guest", requestJsonObject)
)
),
guestJsonElement ->
new NamedBlocOfNameds<>(
"guest",
List.of(
new IsEmail(
new AsString(
new Required(
new IndexedValue("email", guestJsonElement)
)
)
)
),
Guest.class
)
)
),
OrderRegistrationRequestData.class
)
)
.result();
}
}
|