/    Sign up×
Community /Pin to ProfileBookmark

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>
[/CODE]

I am pretty bad with JavaScript but I can understand most html

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@holyhttpSep 15.2012 — 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
Copy linkTweet thisAlerts:
@zggz12authorSep 15.2012 — Thank you, this is exactly what I was looking for.
Copy linkTweet thisAlerts:
@zggz12authorOct 05.2012 — 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?
×

Success!

Help @zggz12 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...