www.webdeveloper.com
+ Reply to Thread
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2012
    Posts
    3

    Disabling submit button unless certain elements are in forms

    I currently have a form that I would like to use JavaScript to disable the submit button unless both fields have more than 3 values, and neither have anything except for A-Z, a-z, and 0-9.

    I currently have
    Code:
    <form action=submit.php method=POST />
    <input type=text name=username />
    <br>
    <input type=password name=password />
    </form>
    I am pretty bad with JavaScript but I can understand most html

  2. #2
    Join Date
    Nov 2006
    Location
    Oakland
    Posts
    494
    Do you meant the username and password have each at least 3 characters?
    Instead of disabling the submit button, why not just prevent the form from being submitted unless all required fields are valid.

    HTML:
    <form action="submit.php" method="POST" name="loginform" onsubmit="return validateForm()" />
    <input type="text" name="username" />
    <br>
    <input type="password" name="password" />
    <br>
    <input type="submit" value="login"/>
    </form>

    JavaScript:

    function validateForm(){
    var reg=/[a-zA-Z0-9]{3,}/i

    if(document.loginform.username.value.search(reg)==-1){
    alert('Your username must be at least 3 alphanumeric characters');
    document.loginform.username.focus();
    return false;
    }
    else if(document.loginform.password.value.search(reg)==-1){
    alert('Your password must be at least 3 alphanumeric characters');
    document.loginform.password.focus();
    return false;
    }

    return true;
    }

    The function above can be optimized but this is a good start.
    Notice all attributes values in the HTML are between quotes and the form is given a name and/or an ID.
    The first step is getting the habit to write a clean HTML

  3. #3
    Join Date
    Sep 2012
    Posts
    3
    Thank you, this is exactly what I was looking for.

  4. #4
    Join Date
    Sep 2012
    Posts
    3
    I have one more question,
    how would I make it so that a third field (ip2) would work with nothing, or a correctly formatted ip address?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Bookmarks

Posting Permissions

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



Recent Articles