views:

366

answers:

2

I want to validate the fields of the list item while adding/editing and stop the saving operation and provide the error information what the user made on that page itself.

For ex, if I want to prevent user not to leave few fields set before saving based on particular status of another field, I cannot make the field as mandatory.

A: 

You will likely have to start creating custom field controls to make this work. However, once you start down the path of customisation, you have a few options to think about.

You may like to think about either creating a custom asp.net form and coding it to post to the list or consider InfoPath forms.

Nat
+1  A: 

Use PreSaveAction.

Add a javascript function named PreSaveAction to your page (it's best if you are creating a custom List Template and can modify the aspx page that will be used as EditForm and NewForm, otherwise try the Content Editor Web Part or by modifying the Master Page) and do all your custom validation from there.

For example, I just used it on a project where we had three percent fields that had to equal 100%. I used the following javascript and it worked great:

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
    var len = identifier.length;
    var tags = document.getElementsByTagName(tagName);
    for (var i = 0; i < tags.length; i++) {
        var tempString = tags[i].id;
        if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
            return tags[i];
        }
    }
    return null;
}

function PreSaveAction() {
    var top = getTagFromIdentifierAndTitle("input", "TextField", "Top %");
    var middle = getTagFromIdentifierAndTitle("input", "TextField", "Middle %");
    var bottom = getTagFromIdentifierAndTitle("input", "TextField", "Bottom %");
    var valid = (100 == parseInt(top.value) + parseInt(middle.value) + parseInt(bottom.value));
    if (!valid) {
        alert("Top %, Middle %, and Bottom % must equal 100% when added.");
    }
    return valid;
}
Rich Bennema
Hi Rich, Great news. This looks a good workable solution and will give a try.
sankar