Link to home
Start Free TrialLog in
Avatar of EnolaKotrotsos
EnolaKotrotsos

asked on

Check field on submit

hey people

I have this code that runs on form submit

function onSubmitForm() {
    var formDOMObj = document.frmSend;
    if (formDOMObj.attach1.value == "" )
        alert("Please press the browse button and pick a file.")
    else
        return true;
    return false;
}

If the field is empty, you get a message (this is an upload form)
I want to keep .exe and .com and .pdf and such of my server so I need to run a check on that field before it's submited. If someone submits an .exe, it gets rejected with a message.

can someone fix the above code for me? I am terrible in javascript.
It would be cool if I can add more extensions later, but for now a check for .exe and .com would do fine...

Thank you very, very much. it is pretty urgent, therefore 500 points..
kindest regards,
Marco
SOLUTION
Avatar of Batalf
Batalf
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or better. case insensitive

function onSubmitForm() {
    var formDOMObj = document.frmSend;
    if (formDOMObj.attach1.value == "" ){
        alert("Please press the browse button and pick a file.");
        return true;
    }else{
        if(formDOMObj.attach1.value.match(/\.(exe|com|pdf)$/gi)){
            alert('Invalid file type');
            return false;
        }
   
    }
       
    return false;
}
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Typo.

 function onSubmitForm() {
    var formDOMObj = document.frmSend;
    if (formDOMObj.attach1.value == "" ) {
        alert("Please press the browse button and pick a file.")
        return false;
    }
    ext = (formDOMObj.attach1.value).substr(value.lastIndexOf(".")).toLowerCase();
    if (ext == ".exe" || ext == ".com" || ext == ".pdf") {
        alert("exe , com and pdf files not allowed.")
        return false;
    }
    return true;
}
this checks for multiple blanks as well


<script>
function onSubmitForm(){
    var fileName=document.frmSend.attach1.value;
    if (/^\s*$/.test(fileName)){
      alert("Please press the browse button and pick a file.");
      return false;
    }
    else
    if (/\.(exe|com|pdf)$/.test(fileName)){
      alert('Invalid file type');
      return false;
    }    
    return true;
}
</script>
if (/\.(exe|com|pdf)$/i.test(fileName)){

is better as it covers uppercase as well