qwerty
qwerty

Reputation: 75

SharePoint form: PreSaveAction function for multiple fields

I know most people use presave function for form validation by using alert. But in my case, i need to append it so that it looks like standard SharePoint. So I append the validation error and it works fine for one single field, but for multiple fields, it only append the last field that being validate.

Here is my code:

function PreSaveAction(){
    var isValid = 0;
    var tajuk = document.querySelector("input[title='Tajuk Required Field']");
    var status = document.querySelector("select[title='Status Required Field']");
    var lokasi = document.querySelector("input[title='Lokasi Required Field']");
    var tarikhMulaRancang = document.querySelector("input[title='Tarikh Mula Rancang']");
    
    // remove validation error if there's any
    if (tajuk.closest('span').lastChild.tagName == 'SPAN')
    {
        if (tajuk.closest('span').lastChild.hasAttributes('role'))      
            tajuk.closest('span').lastChild.remove();
    }   
    if (lokasi.closest('td').lastChild.tagName == 'SPAN')
    {
        if (lokasi.closest('td').lastChild.hasAttributes('role'))
            lokasi.closest('td').lastChild.remove();
    }
    if (tarikhMulaRancang.closest('table').lastChild.tagName == 'SPAN')
    {
        if (tarikhMulaRancang.closest('td').lastChild.hasAttributes('role'))
            tarikhMulaRancang.closest('table').lastChild.remove();
    }

    const errorSpan = document.createElement('span');
    errorSpan.innerHTML = `<span role="alert">Please ensure you fill in required* fields.<br></span>`;
    errorSpan.classList.add('ms-formvalidation');
    errorSpan.classList.add('ms-csrformvalidation');
    
    // check required field based on status
    if(status.value == "Perancangan"){
        
        if (tarikhMulaRancang.value == "") {    
            
            tarikhMulaRancang.closest('table').append(errorSpan);
            isValid++;
        }
    }
    
    // check required field
    if (tajuk.value == "") {    
            
        tajuk.closest('span').append(errorSpan);
        isValid++;
    }
    if (lokasi.value == "") {   
            
        lokasi.closest('td').append(errorSpan);
        isValid++;
    }
    
    if(isValid > 0 )
        return false;
    else
        return true;
}

Upvotes: 0

Views: 38

Answers (0)

Related Questions