Validate all date fields on onsubmit client script

Raviteja K
Tera Expert

I need to write on submit client script which will validate all date fields on a form(nearly 10 fields) to restrict past date.

6 REPLIES 6

Jace Benson
Mega Sage

Should be a simple onsubmit script

This script I've used to verify a variable is after a certain date

https://blog.jacebenson.com/post/2017-09-25-useful-client-scripts/#validate-date-is-after-a-variable

But you could modify it to be something like;

function onSubmit() {
    //validate that the dates are before now
    var now = new Date();
    var dt1 = getDateFromFormat(g_form.getValue("end_date_time"), g_user_date_time_format);
    if (dt1 > now) {//if dt1 bigger then now
        g_form.hideAllFieldMsgs();
        g_form.addErrorMessage("Dates must be befow now.");
        return false;
    }
}

If you use this you'll need to add a dependency for SP to calander.js as noted here: https://blog.jacebenson.com/post/2018-08-16-sp-g_user_date_format/

Thank you for your response, I have 10 date fields on same form. Can we write single validation for all date fields?

Sure;

function onSubmit() {
    //validate that the dates are before now
    var date_variables = [
      'dt1',
      'dt2',
      'dt3',
      'dt4',
      'dt5',
      'dt6',
      'dt7',
      'dt8',
      'dt9',
      'dt10',
    ];
    var now = new Date();
    // iterate over the vars
    var resultsArr = date_variables.map(function(field){
        if (dt1 > now) {//if dt1 bigger then now
            return false;
            // you could note the field witht he error
            g_form.hideFieldMsg(field, true);
            g_form.showFieldMsg(field, "Date must be in the past","error",false);
        } else {
            return true;
        }
    });
    if(resultsArr.indexOf('false')>=0){
        return false;//disallow submit
    }
}

Thank you and really appreciate your help, client is looking for a script which picks date fields dynamically from the catalog item, since in future if they add new date field on that form so there should not be any code change required. Thank you and sorry for the missing clarity in asking my query.