A form handler
This program receives a contact form. It checks the email address and returns a short HTML page.
<?nvs// This program reads a contact form, checks it, and returns an HTML page.#[Core\Json\Derive]class Contact{ public tainted string $name; public tainted string $email; public tainted string $message;
public function constructor(tainted string $name, tainted string $email, tainted string $message) { $this->name = $name; $this->email = $email; $this->message = $message; }}
// `formFieldsAs` fills a `Contact` from the form fields with the same names.// Text from a form is `tainted`, because it comes from outside the program.Contact $form = Core\Request::formFieldsAs<Contact>();
if (!Core\Validate::isEmail($form->email)) { Core\Response::setStatus(422); echo html`<p>Please enter a valid email address.</p>`, "\n";} else { // An `html` template escapes each value, so a `<` in the name is shown as text. tainted string $name = $form->name; echo html`<p>Thank you, {$name}. We will answer soon.</p>`, "\n";}<p>Thank you, Ada <L>. We will answer soon.</p>The output above is the response to a form with the name Ada <L>, the email ada@example.com and
the message Hello. The < and > in the name are shown as text, not as HTML.
Start the server with nvs serve form-handler.nvs. Then send a form with this command:
curl -d "name=Ada&email=ada@example.com&message=Hello" http://127.0.0.1:8000/contactHow it works
Section titled “How it works”Core\Request::formFieldsAs<Contact>() reads the form fields into a Contact object. Each property of
the class reads the form field with the same name.
Text from a form is tainted string, because it comes from outside the program. Code that uses a
tainted value as a plain string does not compile.
Core\Validate::isEmail returns true when the text is a valid email address. If it is not, the
program sets the status 422 and returns a message.
An html template escapes every value you put into it. A visitor cannot add their own HTML or
JavaScript to the page.
