Home > OS >  Expressjs required form elements
Expressjs required form elements

Time:06-29

I am making a sign-up page for my site. It looks like this

<!DOCTYPE html>
<html lang="en" height="">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MVC | Signup</title>
</head>
<body>
  
  <div>
    <form action="/signup" method="post" target="nothing">
      <h1>Sign up for Post-it</h1>
      <input type="text" name="name" placeholder="Your name">
      <input type="text" name="usr" placeholder="Username" >
      <input type="password" name="psd" placeholder="Password">
      <button type="submit">Sign up for post-it</button>
    </form>
  </div>
  <iframe name="nothing" style="display:none"></iframe>
</body>
</html>

But right now, you can create an account without a username or password. I tried the required attribute. It made something like this.

<!DOCTYPE html>
<html lang="en" height="">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MVC | Signup</title>
</head>
<body>
    <form action="/signup" method="post"  target="nothing" onsubmit="alert('form submitted')">
      <h1 >Sign up for post-it</h1>
      <input type="text" name="name" placeholder="Your name" required>
      <input type="text" name="usr" placeholder="Username" required>
      <input type="password" name="psd" placeholder="Password" required>
      <button type="submit">Sign up for post-it</button>
    <iframe name="nothing" style="display: none"></iframe>
</body>
</html>

This works, but the "please fill out this field" doesn't look that great. And if someone figures out how to bypass the required fields, that will do a lot of damage to my database. So is there a way to make sure the form isn't empty on the server side? Note: I'm also using ejs, so you can make error messages like this:

app.get('/error', (req, res) => {
   res.render('signup', { error: 'enter a username'}); // Could also be "enter your name", or "enter your password".
});

CodePudding user response:

You can use Express Validator here is the docs

https://express-validator.github.io/docs/

  • Related