Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(NcSelect): Add required attribute for native form validation #5225

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/components/NcSelect/NcSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,64 @@ export default {
</style>
```

### Native form validation example

```vue
<template>
<div class="container">
<form class="container__form" @submit.prevent>
<NcSelect class="container__select"
input-label="Require a selection"
:options="options"
v-model="singleValue"
required />
<NcButton native-type="submit">Submit</NcButton>
</form>

<form class="container__form" @submit.prevent>
<NcSelect class="container__select"
input-label="Require at least one selection"
:options="options"
v-model="multiValue"
multiple
required />
<NcButton native-type="submit">Submit</NcButton>
</form>
</div>
</template>

<script>
export default {
data() {
return {
options: ['foo', 'bar', 'baz', 'qux', 'quux'],
singleValue: null,
multiValue: [],
}
},
}
</script>

<style>
.container {
display: flex;
gap: 0 12px;
}

.container__form {
display: flex;
flex-direction: column;
align-items: flex-end;
width: 100%;
gap: 8px 0;
}

.container__select {
width: 100%;
}
</style>
```

### No wrap example

The `noWrap` prop is set to `true` and the `max-width` of the multiselect
Expand Down Expand Up @@ -470,6 +528,7 @@ export default {
<template #search="{ attributes, events }">
<input :class="['vs__search', inputClass]"
v-bind="attributes"
:required="inputRequired"
v-on="events">
</template>
<template #open-indicator="{ attributes }">
Expand Down Expand Up @@ -897,6 +956,14 @@ export default {
default: null,
},

/**
* Enable if a value is required for native form validation
*/
required: {
type: Boolean,
default: false,
},

/**
* Any available prop
*
Expand All @@ -922,6 +989,14 @@ export default {
},

computed: {
inputRequired() {
if (!this.required) {
return null
}
// The <input> itself does not have any value so we set the `required` attribute conditionally
return this.value === null || (Array.isArray(this.value) && this.value.length === 0)
},
Comment on lines +992 to +998
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice solution


localCalculatePosition() {
if (this.calculatePosition !== null) {
return this.calculatePosition
Expand Down
Loading