views:

516

answers:

4

I am implementing a custom list definition that contains several columns. A requirement to one of the columns is, that it can only contain unique values. If a user enters a value that is already present in another list item, a validation error must be shown.

Are there any options for doing this OOTB, perhaps in the list definition or in a custom field type? Or do I need to implement this functionality myself?

+3  A: 

To ensure unique values in a column you have two possiblies.

  1. You can override the Validate() method for your field type, and query the list for items with the same value and set the IsValid property accordingly.

  2. Write your own ItemAdding and ItemUpdating eventreceivers to query the list.

Brian Jensen
A: 

Take a look at this form validation related post, not your desired one yet it may shed some light on you.

A: 

I have used the following in the past.

  /// <summary>
            /// Override Validation to check to see if our list already contains an item with the same value
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            public override string GetValidatedString(object value)
            {
                // Get Current List
                SPList thisList = ParentList;

                SPQuery keywordQuery = new SPQuery();

                // Check to see if the current field contains the value entered into field
                keywordQuery.Query = string.Format("<Where>" +
                         "<Eq>" +
                            "<FieldRef Name='{1}' />" +
                            "<Value Type='Text'>{0}</Value>" +
                         "</Eq>" +
                   "</Where>", value, InternalName);

                SPListItemCollection liKeywords = thisList.GetItems(keywordQuery);

                // Will return greater than 0 if it finds the value in the list
                if (liKeywords.Count > 0)
                {
                    // checks to see if the list item is being updated, if it is the same finds the same ID as the one being Validated
                    if (liKeywords[0].ID != SPContext.Current.ItemId)
                    {

                        // Show error message
                        throw new SPFieldValidationException(string.Format("An item called '{0}' already exists", value));
                    }
                }

                // return entered value if unique
                return base.GetValidatedString(value);
            }

HTH Phill

Phill Duffy
A: 

There is an open source feature called "Unique Column Policy" available at http://www.codeplex.com/features, it will solve your problem without creating a dependency on a new field type.

JMD