[Vue] Address Validation

Introduction

During my internship, my first task was to develop an address validation component that accepts a name, phone number, and address.

This component is designed for address recognition in a Chinese context.

Structure

The component includes an input field for entering the address information and a button to trigger the verification process.

The information will be divided into three sections, as shown in the image below.

In code, it should look like this:

1
2
3
4
5
6
7
8
9
userInfo = {
name: 'Tea',
phone: '19283746573',
address: {
province: '上海市',
city: '上海市',
district: '静安区'
}
}

But how can we make this happen?

Flow Chart

Step 1: Split the string into three sections: [“name”, “phone”, “address”].

Step 2: Split the address string into: [“province”, “city”, “district”, “details”].

Let’s Code!

Create an HTML structure to display the content.

Add a textarea element bound to the variable userInput and a button element with a click event that triggers the parseAddressInfo function.

1
2
3
4
5
6
7
8
<div>
<textarea
type="textarea"
placeholder="Paste or enter text to automatically detect name, phone number, and address."
v-model="userInput"
/>
<button type="button" @click="parseAddressInfo">Validate</button>
</div>

1. Extract Basic Information

Begin the script section using setup to define the required variables.

1
2
3
4
5
6
7
8
<script setup>

// receive input
const userInput = ref('');
// define separators; the order is important!
const separators = [", ", " ", ","]

</script>

Then, move on to the function section to implement the core logic!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script setup>
function parseAddressInfo(){
let input = userInput.value;
let basicInfo = {
name: "",
phone: "",
address: ""
}

// Identify the phone number first.
let separator = separators.find(separator => input.split(separator).length > 1);

// Ideal: Information is divided by separators!
if (separator){
input = input.split(separator);
// Extract the phone
basicInfo.phone = input.find(part => /^\d+$/.test(part));

// Unfortunately, there are no separators.
}else{
// Here, I use the Chinese mobile number prefix for detection
const telRegex = /(\+?86)?(1[3-9]\d{9})/;
const telMatch = input.match(telRegex);

if(telMatch){
// If a phone number is detected, save it and then replace it with a blank
basicInfo.phone = telMatch[0];
input = input.replace(basicInfo.phone, " ").trim();
}
}


}
</script>

2. Parse Address Components