CJ

The circle of life – ** .Net – Training – MOSS **

  • Past Post

  • Vistor Locations

Regular Expression Validation Custom Field Type

Posted by Clayton James on May 15, 2007

I have been reading Todd Bleekers book Developers Guide To Windows SharePoint Services 3.0 and came across a great implementation in creating a custom field type in WSS 3.0. This custom field type is a Regular Expression Validation Custom Field Type. I love this implementation as it can be used for many situations…anywhere you want to validate input using regular expressions.

  • Emails

  • Telephone numbers

  • Address

  • Numbers only

  • Letters only

  • Alphanumeric only

If you are after a regular expression to validate input then this is one of the best sites to use.

Here are a couple of screen shots that displays the objective.



A Custom Field Type is a class that is complied into an assembly, so the first thing to do is open VS.NET 2005 and create a new Class Library project.

  • Provide a meaningful project name

  • You need to add an assembly reference to Windows SharePoint Services 12.0.0.0 in the .Net project.

  • Rename the default class Class1.cs to RegExTextField.cs. (VS.NET will refactor the project to update the related references to the new class name)

  • Add two directives to the top of the class.

    • using Microsoft.SharePoint

    • using System.Text.RegularExpressions

  • You need to now inherit functionality so it behaves like a CFT. There are many different CFT classes you can inherit from to get different behaviour, but we want to inherit the SPFiledText as this most resembles our CFT. So the declaration will look like the following

    • public class RegExTextField : SPFieldText

  • WSS v3 will call into one of two constructors so the class must implement both of them even though they don’t implement any code.

    • public RegExTextField(SPFieldCollection fields, string fieldName)
      : base(fields, fieldName)
      { }

    • public RegExTextField(SPFieldCollection fields, string typeName, string displayName)
      : base(fields, typeName, displayName)
      { }

  • The GetValidatedString method converts the field type value into a validated serialised string. We can use this method to create our own custom validation from the value entered. Insert this after the second constructor.

    public override string GetValidatedString(object value)
    {
        string textValue = value.ToString();

    //Only compare RegEx if a value is present
    if (textValue.Length > 0)
    {
        //setup regex based on custom property
        Regex reg = new Regex(GetCustomProperty(“RegularExpression”).ToString(), RegexOptions.IgnoreCase);

        //if the value entered does not match
        if (!reg.IsMatch(textValue))
        {
            throw new SPFieldValidationException(GetCustomProperty(“ExceptionMessage”).ToString());
        }
        else
        {
            return textValue;
        }
    }
    else
    {
        return textValue;
    }
}

  • Sign the assembly so it can be deployed to the GAC. You can sign the assembly by navigating to the Class Library project properties and click the Signing tab. Build the project to produce the assembly and deploy to the GAC.

Now you need to define what elements you want displayed when the CFT is used in the Create Column and Additional Columns Settings.

  • In the same Class Library project choose Add àNew Item and select XML File.
  • In the Name field type fldtypes_RegExTextField.xml. (The name of the file is important as CFTs must begin with fldtypes)
  • Add the following code to your .xml file

    <?xml version=”1.0″ encoding=”utf-8″ ?>
    <FieldTypes>
        <FieldType>
            <Field Name=”TypeName”>RegExTextField</Field>
            <Field Name=”ParentType”>Text</Field>
            <Field Name=”TypeDisplayName”>
                Single line of text (with RegEx validation)
            </Field>
            <Field Name=”FieldTypeClass”>
                CustomFieldTypes.RegExValidation.RegExTextField,
                CustomFieldTypes.RegExValidation, Version=1.0.0.0,
                Culture=neutral, PublicKeyToken=d7f772d26282eb60
            </Field>
            <PropertySchema>
                <Fields>
                    <Field Name=”RegularExpression” DisplayName=”Regular Expression” MaxLength=”255″ DisplaySize=”35″ Type=”Text”>
                        <Default></Default>
                    </Field>
                    <Field Name=”ExceptionMessage” DisplayName=”Exception Message” MaxLength=”255″ DisplaySize=”35″ Type=”Text”>
                        <Default></Default>
                    </Field>
                </Fields>
            </PropertySchema>
        </FieldType>
    </FieldTypes> 

    • The FieldType elements define the attributes associated with the CFT when it appears in the Name and Type section of the Create Column page.
    • The PropertySchema elements define the attributes associated when it appears in the Additional Column Settings (after you select the CFT radio button)

  • CFT have two scopes, Farm or List.

    • Farm: fldtypes*.xml files reside in the ..\12\Template\XML folder.
    • List: The schema.xml file that defines a list template can include CFTs.
  • Because this CFT will be useful across the farm we will copy it to the ..\12\Template\XML folder In Windows Explorer copy the fldtypes_RegExTextField.xml to ..\12\Template\XML.
  • Now all you have to do is perform an application pool recycle, then go to any WSS 3.0 list and add a new column and you will see your CFT.

Now you can use your new WSS 3.0 RegEx Validation CFT in many situations.

48 Responses to “Regular Expression Validation Custom Field Type”

  1. Mick said

    Nice one Clayton – very clear and concise example.

    Good to get it all in one spot.

    🙂

  2. Ramesh said

    Great article. Was very useful.

    I tried adding the dll to bin instead of GAC.(For my application, i dont want to add CFT in GAC because validation is for a site.) Is it possible to add the dll to bin. I tried it but it is not working.

    Let me know if this is possible.

  3. srikanth said

    hi
    iam srikanth
    i got one doubt when i seeing this article,
    my doubt is class name written as “RegExTextBox” in next line ,we call the constructor with name of “RegExTextField” but as per oops class name constuctor must be same.

  4. rk said

    How can we implement CFT for user profiles in Central Administration?

    Thanks!!

  5. CJ said

    Hi Ramesh,

    CFTs must be deployed to the GAC, they cannot be deployed to the bin directory.
    cheers
    CJ

  6. CJ said

    Hi Srikanth,
    You are correct. I have updated the article.
    Much appreciated.

  7. CJ said

    Hi Rk
    User Profiles are implemented differently, i.e. they are not stored in a list that you can define. User Profiles are edited by users from their My Sites and the editing takes place on a page in the _layouts directory called ProfileEdit.aspx (or EditProfile.aspx…I forget).
    You would need to implement validation on this page to receive similar results.

  8. rk said

    HI CJ,

    Lets say, I have created a custom property called SSN in user profile. I want to validate the input and show a message “Invalid SSN number” in case user gives the wrong input?

    Can we achive this using CFT… if not can you suggest any other way?

  9. Suvarna said

    Hi CJ,

    I have a requirement where i need to create a custom field type for DateTime. I want the date entered to be limited to 6 months. I tried to use the same code given in your article and inherited from datetime instead text. It works when i save the document. But when i try to edit the properties of the document i get Invalid cast error.

    any idea why i might be getting the error.. Following is the code that i am trying to test.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint;
    using System.Web;
    using System.Web.UI;
    using Microsoft.SharePoint.Utilities;

    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Publishing;
    using System.Globalization;

    namespace CustomDateTimeFldType
    {
    public class CustomDateTimeField : SPFieldDateTime
    {
    public CustomDateTimeField(SPFieldCollection fields, string fieldName) : base(fields, fieldName)
    {

    }
    public CustomDateTimeField(SPFieldCollection fields, string typeName, string displayName)
    : base(fields, typeName, displayName)
    { }

    public override string GetValidatedString(object value)
    {

    string textValue = value.ToString();
    DateTime expirationDate = (DateTime)Convert.ChangeType(textValue, typeof(DateTime));

    if (expirationDate > DateTime.Today.AddDays(Double.Parse(GetCustomProperty(“NoOfDaysToLimit”).ToString())))
    {

    throw new SPFieldValidationException(“Date Entered is more than 6 months”);

    }
    textValue = expirationDate.ToOADate().ToString();
    return base.GetValidatedString(expirationDate.Date);

    }

    }
    }

  10. Lin said

    Hi CJ,

    I followed your instruction to build the code, added to dll to GAC, add fldtypes_RegExTextField.xml to ..\12\Template\XML folder.

    then I go to my sharepoint site, I am able to click Single line of text(with RegEx validation) check box, get the Regular Expression and Exception Message textbox, but once I click the OK button, I got the following error message:
    “Field type RegExTextField is not installed properly. Go to the list settings page to delete this field”

    I double checked the code, I did not see anything wrong…

    Any idea?

    Thanks a lot for any help!

    lm

  11. Alex said

    Hi CJ,

    I followed your example, but after creating the column with my custom field type, from the column properties edition form i can’t see the values i set in the properties of the propertie schema, i only see a string like “RegularExpression: field value.”

    Thanks for any help

  12. Virandar said

    “Field type RegExTextField is not installed properly. Go to the list settings page to delete this field”

    Can any body explain why this error is coming and what is its resolution
    Thanks in Advance
    Vir

  13. Virandar said

    Error:

    “Field type RegExTextField is not installed properly. Go to the list settings page to delete this field”

    Can Anybody provide the resolution as it is very urgent for me to implement it today.

    Regards
    Vir

  14. KP said

    Virandar –

    You should check the internal name of all of your columns. Anytime you are using CAML you must use internal names and if you add a value to a field whose name consists of multiple words (for instance “Last Name”) the field should be referred to with a “_x0020_” separating the words (for example “Last Name” becomes “Last_x0020_Name”).

  15. Virandar said

    Hi KP,
    What exactly I am trying to implement is the new Custom Field Type,which I suppose does not loop up with any of the column names.I am trying to validate a Year using Regular expression as client side validation which i am incorporating using CFT[SIngle line of text(Year validation)].It is getting displayed in the List settings,but when i am trying to add a new column with this CFT (giving values in Regular Expression and Warning Message Field),it is generating error

    “Field type RegExTextField is not installed properly. Go to the list settings page to delete this field”
    .I don’t know if there is anything missing in this.I followed the exact steps given in the above mail

    Thanks for help in advance
    vir

  16. Virandar said

    Any pointers or solution to my problem for craeting custom field types using Regular expression

  17. CJ said

    Hi Alex,
    This was a know issue with custom field properties. Microsoft has released a hotfix.
    http://support.microsoft.com/kb/932055

    cheers

  18. CJ said

    Hi Lin

    Check your RegExTextField class you created and make sure it is in the GAC. Also check your fldtypes_RegExTextField.xml file and the class reference is correct.

    cheers

  19. CJ said

    Hi Virandar

    Please read what I posted above. It sounds like it can’t make a connection to the class that is installed in the GAC.

    Check your class names are spelt correctly in the fldtypes_RegExTextField.xml file.

    You can also check your log file in the 12 hive for more info. This may identify the issue.

    cheers

  20. Virandar said

    How can we use custom client side validation using regularexpression in mOSS 2007.I want to validate Year,Email on the client side.When i tried to do in the HTML code in sharepoint designer using custom list form,it was giving unexpected error occured.If any body can provide the steps for doing that exactly.

    Thanks CJ,I will see my code to crosscheck what you have mentioned

    Thanks
    Vir

  21. Wes Smith said

    Vir,

    I also got the (un)helpful “is not installed properly” message for no apparent reason. I checked the code and xml and couldn’t find anything wrong. Restarted webserver with no effect. Finally removed it from the GAC and reinstalled it and the error message went away.

    Note this shouldn’t have had any effect since I’d rebuilt it and use the /f flag to force a reinstall… however a reinstall in the GAC apparently isn’t the same as removing and installing to make sure its using the latest code….

    Here are the commands I used. I didn’t change anything else and now my custom type is working.

    “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\GacUtil.exe” /u

    “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\GacUtil.exe” /nologo /i “C:\Documents and Settings\wes\My Documents\Visual Studio 2005\Projects\CustomFieldType\bin\Debug\CustomFieldType.dll” /f

  22. Although it is installed in the GAC, You may still need to add it as a safe control in the web config. If you create a solution for your field type this will be handled for you.

  23. RC said

    I’ve built my CFT in the same manner as described in Todd Bleeker’s book(as described in this article), gone though all of the comments and tried them, and still get the “Field type RegExpTextField is not installed properly. Go to the list settings page to delete this field.” error when I try to add a column with the new type. Has anyone got any other suggestions?

    Thanks

    RC

  24. Sean Looper said

    I’ve got my custom field working just fine. Can add to lists and everything. The problem I ran into is that whenever I want to edit a column, my custom property values are not persisted in the edit page. Here is an example using two custom properties “ListName” and “FieldName”:

    Create Page:

    List Name: My List
    Field Name: My Field

    Edit Page:

    List Name: List Name field value.
    Field Name: Field Name field value.

    Do you have this same problem when editing your Regex Columns?

  25. Negin said

    Hi Sean,

    I have the same problem, did you ever get it to show the correct values when you edit the column?

  26. CJ said

    Hi Negin & Sean
    Please see my previous comment.
    This is the symptom:
    You create a list that contains a custom field that has a custom field type on a Microsoft Windows SharePoint Services 3.0 Web site. When you try to edit the properties of the custom field on the FldEditEx.aspx page, you cannot select the values for the custom field. Instead, you see only the default text in the custom field.

    There is a hotfix for this issue.
    http://support.microsoft.com/kb/932055

  27. A Workaround for SharePoint Property Bug in Custom Field Types

    Recently, I was working on developing custom field types a …

  28. CV said

    I am getting an error

    Field with name “” was not found.

    Any suggestions?

  29. CV said

    Got it worked!!

    another questions is weather we can validate these fields at the client side rather than having a server post back of the page?

    Anyone?

  30. naisioxerloro said

    Hi.
    Good design, who make it?

  31. Jaco van Eeden said

    I received the “…not installed properly” error, and here is my version of the fix.

    Please note that it might sound like obvious things to do, but I am new to Sharepoint, so I made the obvious mistakes.

    Firstly, change the PublicKeyToken in the XML from the one that is provided in the code example to the one that is assigned to the dll. To find out what the token is, either open the GAC and find the dll, or use command prompt.

    Secondly, change the RegExValidation in the XML to the name of your Namespace.

    Third, remove the CustomFieldTypes from the XML file.

    That should leave you with a XML file that loos something like this:

    RegExTextField
    Text

    Single line of text (with RegEx validation)

    <>.RegExTextField,
    <>, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=<>

    Save XML file and close.

    Recycle Application pool (or reboot server if you *really* want to make sure).

    See if it works… ^_^

    I hope this can be of help to other newbies, or people that just overlooked something.

  32. Jaco van Eeden said

    Oh crap… The XML did not display…

    Anyway, here is a second attempt.

    RegExTextField
    Text

    Single line of text (with RegEx validation)

    Namespace.RegExTextField,
    Namespace.SPRegExValidator, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=YourPublicKeyToken

    Sorry…

  33. Jaco van Eeden said

    Color me confused…

    What I am trying to say is that the FieldTypeClass’s content should read something to this extent:

    <>.RegExTextField,
    <>, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=<>

    Again, my apologies for the previous comments that does not display properly.

    I did use the Code tags, I promise.

  34. gavinbarron said

    Great article Clayton!

    It’s gone straight into my del.icio.us

  35. Ned said

    I am able to update the Regular and Exception Message in the fldtypes*.xml but how would update the Description and make the Custom Field Type Required = “True”?

  36. Cindy Rodriguez said

    This is wonderful! Thank you for such a great job. You have just saved many people hours of work and this is a great introduction to developing with SharePoint.

    Thanks again!

  37. Cindy Rodriguez said

    Jaco Van Eeden, thank you so much for providing that information. I’m new to SharePoint too and your explanations were exactly what I needed to fix the problems I was having.

  38. surya said

    Hi CJ,

    I have created a custom field type using a usercontrol (ListBox control). The field is created and also attached to any custom list successfully. But when i try to add a new item to the list and save, it gives me a “null object exception”. I find that my listbox control doesn’t get initialized somehow. Have u come across such a situation or do you have any ideas as to what might be missing ?

    Thanks in advance and great article u have here.

  39. kisha said

    can any one pls tell me what are available types like type=”Text”
    n from where i can find out these type
    like if i want show a dropdown or check box or radiobutton etc
    thnks

  40. Sellers said

    This is the error I am recieving when I try to add the new field…
    Name cannot begin with the ‘3’ character, hexadecimal value 0x33. Line 1, position 104

    any help???

  41. […] Todd’s RegEx: https://claytonj.wordpress.com/2007/05/15/regular-expression-validation-custom-field-type/ […]

  42. […] Todd’s RegEx: https://claytonj.wordpress.com/2007/05/15/regular-expression-validation-custom-field-type/ […]

  43. Mad_Boy3007 said

    “Field type RegExTextField is not installed properly. Go to the list settings page to delete this field”

    I researched lot and finally got the solution. Actually this problem is coming due to wrong Namespace specification in following line :

    CustomFieldTypes.RegExValidation.RegExTextField,
    CustomFieldTypes.RegExValidation, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=d7f772d26282eb60

    Please make changes according to your namespace, the syntax goes like this:

    YourDefaultNamespace.YourFieldClassName,
    YourAssemblyName, Version=dll_VersionInAssembly,
    Culture=neutral, PublicKeyToken=PublicTookenInAssembly,

    try this it will resolve this error.

  44. […] https://claytonj.wordpress.com/2007/05/15/regular-expression-validation-custom-field-type/ […]

  45. Kumarakom said

    Kumarakom…

    […]Regular Expression Validation Custom Field Type « CJ[…]…

  46. Website Design and Web Development Company | Bluewire Technologies Bangalore…

    […]Regular Expression Validation Custom Field Type « CJ[…]…

  47. There are certainly plenty of particulars like that to take
    into consideration. That is a nice level to carry up.

    I offer the thoughts above as normal inspiration however clearly there are questions
    just like the one you bring up where a very powerful factor will probably be working in
    trustworthy good faith. I don?t know if finest practices have
    emerged round issues like that, but I’m sure that your job is clearly identified as a good game. Each girls and boys feel the influence of only a second’s pleasure, for the rest of their lives.

  48. Custom Field Type Webcast from San Antonio SharePoint User Group

    Travis Lingenfelder gave a presentation today by Live Mee …

Leave a reply to kisha Cancel reply