lilvenus
lilvenus

Reputation: 43

Need to make a sharepoint field required programmatically

I am using a standard sharpoint form, I have code that displays a tracking number once the user selects "completed" on the "Status" dropdown. All of it functions, what i need to do at this point is make the tracking number required once they select completed. If i make the field required via sharepoint and then try to hide it sharepoint will not save the task :/ Here is my code:

$(document).ready(function () {    
var statusField = SPUtility.GetSPField('Status');  
var showOrHideField = function() {
    var statusFieldValue = statusField.GetValue();       
    if(statusFieldValue != 'Appeal Mailed') {
        SPUtility.HideSPField('Tracking Number');
    }
    else 
    {              
      SPUtility.ShowSPField('Tracking Number');                            
    }
};
 showOrHideField();

$(statusField.Dropdown).on('change', showOrHideField);
});

Upvotes: 2

Views: 3197

Answers (1)

Thriggle
Thriggle

Reputation: 7059

Here are a couple options:

Option 1: List Validation Settings

This can be accomplished non-programmatically using SharePoint 2010's list validation settings. (Go to List Settings -> Validation Settings.)

You can add an Excel-like formula that must resolve to true in order for an item to be considered valid.

In your case, the formula would look something like this:

=IF([Status]="completed",NOT(ISBLANK([Tracking Number])),TRUE)

Option 2: Overwrite PreSaveAction()

In JavaScript, you can overwrite the PreSaveAction() function on the edit form to perform a programmatic check before allowing the form to be submitted.

In the function, return true if everything looks good and you want the save to go through, or false to abort the save.

Example:

function PreSaveAction(){
    var statusField = SPUtility.GetSPField('Status');
    var trackingField = SPUtility.GetSPField('Tracking Number');
    var isValid = 
        statusField.GetValue() != "completed" ||
        trackingField.GetValue().length > 0;
     if(!isValid){
        alert("You must enter a tracking number.");
    }
    return isValid
}

Upvotes: 2

Related Questions