In many applications, you need to ensure users select a valid address from the autocomplete suggestions rather than typing freely. This example demonstrates validation patterns that provide clear feedback and prevent form submission with invalid addresses.
Start typing an address and select one from the suggestions. Try submitting the form without selecting an address to see the validation in action.
This validation pattern uses a combination of state tracking and event handling to ensure data integrity.
isValidated boolean that's set to true only when a place is selected from the dropdown via the onResponse callback.onsubmit handler, check if isValidated is true and selectedPlace exists before processing the form.bind:this to get a reference to the component instance, allowing you to call
its clear() method programmatically to reset the input field whilst maintaining
your form's validation state.event.preventDefault() if validation fails, keeping the user on the form to
correct the issue.Here is a simplified version of the validation pattern. Adapt the error messaging and styling to match your application's design system.
<script lang="ts">
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { PlaceResult } from 'places-autocomplete-svelte/interfaces';
let autocompleteComponent: PlaceAutocomplete | undefined = $state(undefined);
let selectedPlace: PlaceResult | null = $state(null);
let isValidated = $state(false);
let submitAttempted = $state(false);
const onResponse = (response: PlaceResult) => {
selectedPlace = response;
isValidated = true;
submitAttempted = false;
};
const handleSubmit = (event: Event) => {
event.preventDefault();
submitAttempted = true;
if (!isValidated || !selectedPlace) {
alert('Please select a valid address from the suggestions.');
return;
}
// Process the validated address
console.log('Validated address:', selectedPlace);
};
const handleReset = () => {
selectedPlace = null;
isValidated = false;
submitAttempted = false;
autocompleteComponent?.clear();
};
</script>
<form onsubmit={handleSubmit}>
<label for="address">Delivery Address *</label>
<PlaceAutocomplete
bind:this={autocompleteComponent}
{onResponse}
options={{ clear_input: false }}
/>
{#if submitAttempted && !isValidated}
<p class="text-red-600">Please select an address from the dropdown.</p>
{/if}
{#if isValidated}
<p class="text-green-600">✓ Address validated</p>
{/if}
<button type="submit">Submit</button>
<button type="button" onclick={handleReset}>Reset</button>
</form>