As with so many things I write about recently I had a need to do something different at my client site. This time I needed to fake a required field on a SharePoint list form. The reason behind it was we had customized the form and had some fields that were required in some cases, but not all. These fields could not be marked as required in the content type because then we would need to fill in default or bogus data into the fields and that wouldn’t look good so I decided to simply make the fields look exactly like a SharePoint required field without actually setting them up that way.
Fake a Required Field on a SharePoint List Form
This may already be documented somewhere, but I didn’t bother to look. I thought the solution I came up with is pretty quick and clean so I wanted to share it. I am basically just inserting the same <span> field that SharePoint does onto a label when the field is set as a required field. Using JQuery I get the <nobr> control and then insert the <span> after. Here’s the code to accomplish that:
/******************************************************************************************** *Function Name: displayAsRequired * *Parameters: $fieldTitle - Title of the field * *Purpose: Makes a control appear as if it were required, without making it required in SP * /********************************************************************************************/ function displayAsRequired(fieldTitle) { var reqField = $(".ms-formlabel nobr").filter(function (){ return $(this).contents().eq(0).text() === fieldTitle; }).after("<span title='This is a required field.' class='ms-accentText'> *</span>"); }
So you just need to pass in the field name (display name, not the internal name) to the function. The code will find the corresponding <nobr> control on the form and update it to look like a required field. Kudos to a comment Marc Anderson made in a blog somewhere about accessing the <nobr> field. I would have done it a bit differently, but I liked the flow of the code in the comment he made.
Thanks for reading!!
Comments
I assume you then used PreSaveAction to ensure it was actually filled in?
M.
Yup. All the validation work is happening in PreSaveAction. The call to this function actually happens on the form setup function which is called using _spBodyOnLoadFunctionNames.push();
You can also use PreSaveAction to conditionally make the value required.
M.
Absolutely, but the PreSave won’t display it on the screen. This shows it on the screen the same as SharePoint does OOTB but allows me to show conditionally. Business required fields to be marked required based on another field. So I used this solution to make it look the same throughout
Actually that’s not true, I could use the PreSave to show it as required after the user attempted to save it and that’s how it was originally coded, but they wanted it shown on the form before the save occurred.