I have a post create method:
void gönderiyiOluştur(HTTPServerRequest istek, HTTPServerResponse yanıt)
{
render!("gönderiler/oluştur.dt")(yanıt);
}
and a post store method like this:
void gönderiyiKaydet(HTTPServerRequest istek, HTTPServerResponse yanıt)
{
auto başlık = istek.form["baslik"];
auto içerik = istek.form["icerik"];
bool yayınla = false;
if (başlık.length > 0)
{
Gönderi gönderi = Gönderi(başlık, içerik);
gönderi.kaydet();
yanıt.redirect("/");
}
else
{
yanıt.redirect("/gönderiler/oluştur");
}
}
I'd like to make basic form validation. For example if input fields are empty it redirects to previous page.
I suppose I should pass some error message to the create method like baslik field should not be empty etc..
But since I am quite new to framework I shouldn't figure out. Are there any facilities does the framework offer for form validation.
Basic form validation is easy when you use the web framework from vibe.d. The basic steps are:
Create a class
Gönderiyi
and put yourkaydet
method inside this class:Define a method inside the class which should be called in case a validations fails. This method should display the error message:
Annotate the
kaydet
method with the@errorDisplay
attribute to connect the method with the error function:Now do the validation inside the
kaydet
method and throw an exception in case of an error. ThegetError
method is then called automatically. You can take advantage of parameter binding and conversion, too. When the D parameter name is the same as the name of an HTML input value, then this value is bind to the D parameter. Automatic type conversion takes place (e.g. toint
) and can lead to exceptions, which are then handled in thegetError
method, too.As last step you need to register your class with the web framework:
You should have a look at the documentation of errorDisplay and at the web framework example from vibe.d, too.