0
0
Vueframework~5 mins

Sanitizing user input in Vue

Choose your learning style9 modes available
Introduction

Sanitizing user input means cleaning what users type to keep your app safe and working well.

When users type text that will show on the page
When saving user data to a database
When sending user input to other systems
When preventing harmful code from running in your app
Syntax
Vue
<template>
  <input v-model="userInput" @input="sanitizeInput" aria-label="User input field" />
  <p>Cleaned input: {{ cleanInput }}</p>
</template>

<script setup>
import { ref } from 'vue'

const userInput = ref('')
const cleanInput = ref('')

function sanitizeInput() {
  // Remove HTML tags and trim spaces
  cleanInput.value = userInput.value.replace(/<[^>]*>/g, '').trim()
}
</script>

Use v-model to bind input value to a variable.

Sanitize inside an event handler like @input to clean as user types.

Examples
Simple inline sanitizing removing HTML tags as user types.
Vue
<input v-model="text" @input="text = text.replace(/<[^>]*>/g, '')" />
Using a separate function to clean input for reuse.
Vue
const sanitize = (str) => str.replace(/<[^>]*>/g, '').trim()

// Use in method
function onInput() {
  clean.value = sanitize(userInput.value)
}
Sample Program

This Vue component lets users type a comment. It cleans the comment by removing any HTML tags and extra spaces as the user types. The cleaned comment shows below the input.

Vue
<template>
  <label for="comment">Enter comment:</label>
  <textarea id="comment" v-model="comment" @input="sanitizeComment" aria-label="Comment input"></textarea>
  <p>Sanitized comment:</p>
  <pre>{{ sanitizedComment }}</pre>
</template>

<script setup>
import { ref } from 'vue'

const comment = ref('')
const sanitizedComment = ref('')

function sanitizeComment() {
  // Remove HTML tags and extra spaces
  sanitizedComment.value = comment.value.replace(/<[^>]*>/g, '').trim()
}
</script>
OutputSuccess
Important Notes

Sanitizing helps prevent security problems like code injection.

Always sanitize on the client and again on the server for safety.

Use accessible labels and semantic HTML for better user experience.

Summary

Sanitizing user input cleans unwanted or harmful content.

Use Vue's v-model and event handlers to sanitize as users type.

Keep your app safe and user-friendly by cleaning input before use.