Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jun 2002
    Posts
    57
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Validate Form Field

    I'm trying to validate a form file field, I need the user to insert a .jpg image, but if they leave the box blank then the field is filled out so that a default image is passed to the next page. I've got the .jpg thing working, but it's the other part I'm struggling with. Here's what I've got so far:

    function validateform() {

    if(Right(document.form1.file.value,3)!="jpg"){
    alert("Please Select a JPG File");
    return false;
    }
    else {
    if (document.form1.file.value == "" ){
    document.form1.file.value = 'no-image.jpg'
    }
    }
    }

    // Works out the last three characters of the file field
    function Right(str, n)
    {
    if (n <= 0) // Invalid bound, return blank string
    return "";
    else if (n > String(str).length) // Invalid bound, return
    return str; // entire string
    else { // Valid bound, return appropriate substring
    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
    }
    }


    <form enctype="multipart/form-data" method="POST" action="article_image.asp" onsubmit="return validateform();" id="form1" name="form1">
    <p><input name="file" type="file" class="narcol" id="file" /></p>
    <p>You can only upload image files with the extension .jpg. </p>
    <p>If you do not have an image for this article, please leave the box blank and click next. </p>
    <p><input name="Submit" type="submit" class="button" value="Next &gt;&gt;" />
    </p>
    </form>

    Thanks

    Chris

  • #2
    Regular Coder
    Join Date
    Sep 2005
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'm not entirely sure what you'r problem is, but here's a possible solution: in the form's onSubmit... onSubmit="if (!validateForm()) { document.getElementById('file').value='default.jpg'; return false;}"


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •