Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Last active May 17, 2022 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatsuyasusukida/fa28e2b0a8bb810b179556a42b946b97 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/fa28e2b0a8bb810b179556a42b946b97 to your computer and use it in GitHub Desktop.
👍 How to validate user input in Node.js [video version available]

👍 How to validate user input in Node.js [video version available]

Video thumbnail: How to validate user input in Node.js

About this article

This article describes how to validate the data entered by the user from the form of the web page.

Workflow

The workflow is as follows:

  1. Preparing for coding
  2. Coding
  3. Operation check

Preparing for coding

Run the following command in the terminal to prepare for coding.

mkdir nodejs-form-validation
cd nodejs-form-validation
npm init -y
npm install --save validator
touch form.js main.js validate.js

Coding

form.js

Open form.js in the editor and enter the following content.

Click to go to form.js

validate.js

Open validate.js in the editor and enter the following content.

Click to go to validate.js

The points are as follows:

  1. Define the makeValidationCompany function that creates the validation result object.
  2. Define a validateCompany function to validate.
  3. Check if you can access req.body.form. Since it is assumed that a req object is passed by Express when calling the validateCompany function, the argument is req instead of form.
  4. isNotEmpty is checked with a regular expression that represents one or more characters other than spaces and tabs.
  5. isKana is checked in Unicode with a regular expression that represents one or more characters in the katakana range.
  6. isDigitsSeven is checked with a regular expression that represents 7 digits.
  7. isDigits is checked with a regular expression that represents one or more numbers.
  8. isUrl is checked using the validator.isURL function.

main.js

Open main.js in the editor and enter the following content.

Click to go to main.js

Operation check

Run the following command in the terminal.

node main.js

The execution result is as follows:

{
  validationFail: {
    ok: false,
    name: { ok: false, isNotEmpty: false },
    kana: { ok: false, isKana: false },
    zip: { ok: false, isDigitsSeven: false },
    address: { ok: false, isNotEmpty: false },
    tel: { ok: false, isDigits: false },
    email: { ok: false, isNotEmpty: false },
    website: { ok: false, isUrl: false }
  },
  validationSucceed: {
    ok: true,
    name: { ok: true, isNotEmpty: true },
    kana: { ok: true, isKana: true },
    zip: { ok: true, isDigitsSeven: true },
    address: { ok: true, isNotEmpty: true },
    tel: { ok: true, isDigits: true },
    email: { ok: true, isNotEmpty: true },
    website: { ok: true, isUrl: true }
  }
}

Check the following two points.

  • All fields contained in validationFail must be false
  • All fields contained in validationSucceed are true

Conclusion

Form validation is troublesome, but it is almost indispensable when input from the person (user) who uses the application is required, and the quality of validation including error message display etc. has a great influence on the uter experience. So we cannot cut corners. It would be ideal if the following functions related to validation could be provided.

  • A clear error message is displayed as soon as the user types it.
  • If an error remains when you press a button such as Next, move to the relevant location.

However, it will take some time to provide these features. For example, in order to be able to display error messages immediately, it is desirable to have separate validation functions for the backend and frontend. However, maintaining consistency between the backend and frontend is not an easy task. In order to save time, it is necessary to make a compromise, such as providing the validation function only on the backend and calling the validation function of the backend from the frontend using fetch etc.

How are you implementing validation? Feel free to comment on your opinions and impressions, and other comments are welcome. Thank you for reading!

/node_modules/
/package-lock.json
# Do not ignore package-lock.json other than gist.
function makeFormCompany () {
return {
name: '',
kana: '',
zip: '',
address: '',
tel: '',
email: '',
website: '',
}
}
module.exports.makeFormCompany = makeFormCompany
const {makeFormCompany} = require('./form')
const {validateCompany} = require('./validate')
if (require.main === module) {
main()
}
async function main () {
try {
const formFail = makeFormCompany()
const formSucceed = makeFormCompany()
formSucceed.name = '株式会社ロレムイプサム'
formSucceed.kana = 'カブシキガイシャロレムイプサム'
formSucceed.zip = '9402039'
formSucceed.address = '新潟県長岡市関原南4丁目3934番地'
formSucceed.tel = '0258945233'
formSucceed.email = 'sales@example.com'
formSucceed.website = 'https://www.loremipsum.co.jp'
const validationFail = validateCompany({body: {form: formFail}})
const validationSucceed = validateCompany({body: {form: formSucceed}})
console.info({validationFail, validationSucceed})
} catch (err) {
console.error(err)
}
}
{
"name": "nodejs-form-validation",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"dev": "node main.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"validator": "^13.7.0"
}
}
const validator = require('validator')
function makeValidationCompany () {
return {
ok: null,
name: {ok: null, isNotEmpty: null},
kana: {ok: null, isKana: null},
zip: {ok: null, isDigitsSeven: null},
address: {ok: null, isNotEmpty: null},
tel: {ok: null, isDigits: null},
email: {ok: null, isNotEmpty: null},
website: {ok: null, isUrl: null},
}
}
function validateCompany (req) {
if (!req || !req.body || !req.body.form) {
throw new TypeError('!req || !req.body || !req.body.form')
}
const validation = makeValidationCompany()
validation.name.isNotEmpty = /^\S+$/.test(req.body.form.name)
validation.name.ok = isValidField(validation.name)
validation.kana.isKana = /^[\u30A0-\u30FF]+$/.test(req.body.form.kana)
validation.kana.ok = isValidField(validation.kana)
validation.zip.isDigitsSeven = /\d{7}/.test(req.body.form.zip)
validation.zip.ok = isValidField(validation.zip)
validation.address.isNotEmpty = /^\S+$/.test(req.body.form.address)
validation.address.ok = isValidField(validation.address)
validation.tel.isDigits = /\d+/.test(req.body.form.tel)
validation.tel.ok = isValidField(validation.tel)
validation.email.isNotEmpty = /^\S+$/.test(req.body.form.email)
validation.email.ok = isValidField(validation.email)
validation.website.isUrl = validator.isURL(req.body.form.website)
validation.website.ok = isValidField(validation.website)
validation.ok = isValidRequest(validation)
return validation
}
function isValidField (validationField) {
return Object.keys(validationField).every((key) => {
return key === 'ok' || validationField[key] === true
})
}
function isValidRequest (validation) {
return Object.keys(validation).every((key) => {
return key === 'ok' || validation[key].ok === true
})
}
module.exports.makeValidationCompany = makeValidationCompany
module.exports.validateCompany = validateCompany
module.exports.isValidField = isValidField
module.exports.isValidRequest = isValidRequest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment