✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🏦 Standard & Poor's chooses Dash Enterprise for ESG analysis. Learn why, sign up for the June 23 Webinar here!

How to do validation on Datatable dropdowns?

I want to do some validation on Datatable dropdown, as I don’t want the user to leave any column blank or not selected. So I need to generate an appropriate alert or Dialog box on it.

Hi @Gourav119

One way to ensure a selection is made is to set clearable=False in the dropdown. In this example, the first column is clearable (the default) and the last column is not clearable:

import dash
import dash_html_components as html
import dash_table
import pandas as pd
from collections import OrderedDict


app = dash.Dash(__name__)

df = pd.DataFrame(OrderedDict([
    ('climate', ['Sunny', 'Snowy', 'Sunny', 'Rainy']),
    ('temperature', [13, 43, 50, 30]),
    ('city', ['NYC', 'Montreal', 'Miami', 'NYC'])
]))


app.layout = html.Div([
    dash_table.DataTable(
        id='table-dropdown',
        data=df.to_dict('records'),
        columns=[
            {'id': 'climate', 'name': 'climate', 'presentation': 'dropdown'},
            {'id': 'temperature', 'name': 'temperature'},
            {'id': 'city', 'name': 'city', 'presentation': 'dropdown'},
        ],        
        editable=True,
        dropdown={
            'climate': {           
                'options': [
                    {'label': i, 'value': i}
                    for i in df['climate'].unique()
                ]
            },
            'city': {
                 'clearable': False,
                 'options': [
                    {'label': i, 'value': i}
                    for i in df['city'].unique()
                ]
            }
        },
        # Two ways to fix alignment
        # css=[{"selector": ".Select-value", "rule": 'padding-right: 42px'}],
        # or
        # style_cell={'textAlign': 'left'},
    ),

])


if __name__ == '__main__':
    app.run_server(debug=True)

image
If you try this example you will see that the text alignment in the non-clearable column is incorrect. (I think it might be a bug) Here are two work-arounds:

  1. Text align left: either style_cell={'textAlign': 'left'}, or use style_data_conditional to apply this only to the dropdown columns.

  2. Add padding: css=[{"selector": ".Select-value", "rule": 'padding-right: 42px'}]