ValidateFieldName

Summary

Returns a valid field name for a database based on a field name and a path to a database. All invalid characters in the input field name are replaced with an underscore. The field name restrictions depend on the type of database.

Syntax

ValidateFieldName (name, {workspace})
ParameterExplanationData Type
name

The field name that will be validated.

String
workspace

The workspace that will be used to validate the field name. The workspace can be a file system, a file, or an enterprise geodatabase.

If the workspace is not specified, the Current Workspace environment will be used. If the Current Workspace environment is not set, a folder workspace will be used.

String
Return Value
Data TypeExplanation
String

A valid field name for the workspace.

Code sample

ValidateFieldName example

A valid field name based on the workspace is returned.

import arcpy
import os

class ShapeError(Exception):
    pass


try:
    # Get the input feature class and make sure it contains polygons.
    in_fc = arcpy.GetParameterAsText(0)
    if arcpy.Describe(input).shapeType != "Polygon":
        # Raise a custom exception
        raise ShapeError("Input does not contain polygons")

    # Get the new field name and validate it.
    field_name = arcpy.GetParameterAsText(1)
    field_name = arcpy.ValidateFieldName(field_name, os.path.dirname(in_fc))

    # Add the new field and calculate the value.
    arcpy.management.AddField(in_fc, field_name, "DOUBLE")
    arcpy.management.CalculateField(
        in_fc, field_name, "!shape.area! / !shape.length!", "PYTHON3"
    )
except ShapeError as err:
    print(err)
except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))

Related topics