Is there a way to validate if a user types a street address with Google autocomplete?

746 views Asked by At

In my signup form I have a field which requires that the user types in his/her address and city (autocomplete).

Problem is that it's also possible for the user to just type his/her city without the street and submit the form.

Does anyone has a solution for this?

<script>
  var input = document.getElementById('adres');
  var autocomplete = new google.maps.places.Autocomplete(input,{componentRestrictions: {country:'be'}});
  google.maps.event.addListener(autocomplete, 'place_changed', function(){
  var place = autocomplete.getPlace();
  })
</script>
2

There are 2 answers

5
Dekel On BEST ANSWER

You can use autocomplete.setTypes(['address']); to allow only addresses in the autocomplete.

A city is not an address (it's a region), so the autocomplete will not allow it.

var input = document.getElementById('adres');
var autocomplete = new google.maps.places.Autocomplete(input,{componentRestrictions: {country:'be'}});
autocomplete.setTypes(['address']);
google.maps.event.addListener(autocomplete, 'place_changed', function(){
    var place = autocomplete.getPlace();
})
1
Emiliano Cervantes On

I'm curious, you ask the person to type the complete address or you separate in various fields? Like one for street, another for state, city, etc, or is it just one field?

If you ask for address and people keep typing just the city for example, divide it in two inputs, one for the address name and another for the number, you could ask for the zip code. The important part is to make them know they need to add their address properly.

Also you could make validations, in the fields you could put "Address must have a '#'" to make sure there's a house number (Idk, that last one was an example)