简体   繁体   中英

Vibe.d basic form validation

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:

  1. Create a class Gönderiyi and put your kaydet method inside this class:

     class Shipment { @method(HTTPMethod.POST) void kaydet() { ... } } 
  2. Define a method inside the class which should be called in case a validations fails. This method should display the error message:

     void getError(string _error = null, HTTPServerResponse res) { ... } 
  3. Annotate the kaydet method with the @errorDisplay attribute to connect the method with the error function:

     class Shipment { @method(HTTPMethod.POST) @errorDisplay!getError void kaydet() { ... } void getError(string _error = null, HTTPServerResponse res) { ... } } 
  4. Now do the validation inside the kaydet method and throw an exception in case of an error. The getError 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 (eg to int ) and can lead to exceptions, which are then handled in the getError method, too.

  5. As last step you need to register your class with the web framework:

     auto router = new URLRouter; router.registerWebInterface(new Gönderiyi); 

You should have a look at the documentation of errorDisplay and at the web framework example from vibe.d , too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM