I am trying to do javascript form validation, and to do this I need to call two functions. One for the password and on for the username (I will also need to call more later on).
Here is my JS code:
function validateUserName(NewUser)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
alert("You left Username field empty");
return false;
}
else if (uLength <4 || uLength > 11)
{
alert("The Username must be between 4 and 11 characters");
return fasle;
}
else if (illegalChars.test(u))
{
alert("The username contains illegal characters");
return false;
}
else
{
return true;
}
}
function validatePassword(pwd, confirmPwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["cP"].value
var pLength = p.length;
if (p == null || p == "")
{
alert("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
alert("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
alert("Th passwords do not match!");
return false;
}
}
and here is my HTML form:
<form name = "NewUser" onsubmit= "return validateUserName(), return validatePassword()" action = "">
<tr>
<td>Username:</td>
<td><input type = "text" name = "user"/></td>
</tr>
<tr>
<td class = "Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" name = "pwd"/></td>
<tr>
<td class = "Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type = "password" name = "confirmPwd"/></td>
<tr>
<td class = "Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type = "submit" value = "Submit"/>
Please ignore the table code.
Should I rather just put it all in one function? Or is there a way to call two functions at once?
You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
onsubmit = function () { if (allowSubmit) allowSubmit = false; else return false; } })(); (well, as sure-fire as you can get with JS enabled anyway). You could disabled the button as a visual confirmation to the end user that the form can only be submit once too. Very correct.
The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.
Hitting enter on text fields can sometimes trigger a form submit. See here. Especially if that is the only element in the form. One way to control the post back is to set the action to empty and fire off the event yourself with Javascript.
You have multiple ways of approaching this, the easiest for your current set up would be:
The following will run both functions no matter what state is returned each time, because they are not executed inline as part of a logical expression which will "short circuit" when getting a false value:
function validateForm(){
var validation = true;
validation &= validateUserName();
validation &= validatePassword();
return validation;
}
And then in your form markup:
<form onsubmit="return validateForm()">
If would probably be advisable, in the interests of making more reusable code, to modify your validation functions so that they accept a form
argument. This would mean you could do the following:
<form onsubmit="return validateForm(this);">
.. and have your receiving function do the following:
function validateForm(form){
var validation = true;
validation &= validateUserName(form);
validation &= validatePassword(form);
return validation;
}
You could also implement this via the preferred way of applying event listeners which is to use addEventListener
instead of the html attribute onsubmit
:
/// wait for window load readiness
window.addEventListener('load', function(){
/// you could improve the way you target your form, this is just a quick eg.
var form;
form = document.getElementsByTagName('form')[0];
form.addEventListener('submit', validateUserName);
form.addEventListener('submit', validatePassword);
});
The above assumes that it's required to support modern browsers. If you wish to support older versions of internet explorer you'd be better off making a function to apply your event handling e.g:
function addEventListener( elm, evname, callback ){
if ( elm.addEventListener ) {
elm.addEventListener(evname, callback);
}
else if ( elm.attachEvent ) {
elm.attachEvent('on'+evname, callback);
}
}
This second option makes it harder to exert a global control over what gets validated, where, when and in what order, so I'd recommend the first option. However I'd would also recommend at least applying your singular submit
handler using the JavaScript method above, rather than using onsubmit=""
.
Simply combine the two with the logical AND operator:
<form name="NewUser" onsubmit="return validateUserName() && validatePassword();" action="">
<tr>
<td>Username:</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td class="Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd"/></td>
<tr>
<td class="Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirmPwd"/></td>
</tr>
<tr>
<td class="Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type="submit" value="Submit"/>
</form>
There are a few approaches to this. One is to create a function, such as submitForm() which then calls your two other functions. Perhaps using those function calls as part of if
statements to provide client side validation.
The other method is to override the default submit functionality of the form, and instead call the functions as you see fit. jQuery provides an easy approach for this. Have a look at http://api.jquery.com/submit/ for more information.
Ideally, the validateUser()
and validatePassword()
functions would be merged into the one function validateUser()
. You may want to provide the code of your current functions for advice on how to do that, if you're stuck...
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With