validation in javascript is not validating the function - javascript

I am validating a form which has validations for required field, character, number, email, password format, length of a field.
In my code, required field and length are working but the rest.
JavaScript code for Password format:
function CheckPassword(paswd) {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if (document.reg_indi_form.pswd.length > 0) {
if (!document.reg_indi_form.pswd.value.match(paswd)) {
submitFlag = true;
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i10').style.fontSize = "12px";
//return false;
}
}
return submitFlag;
}
function alls() {
var valid = true;
valid *= req();
valid *= validateUname();
valid *= CheckPassword(this);
valid *= num();
valid *= confirm_pswd();
valid *= namevalid();
valid *= ValidateEmail(this);
return valid ? true : false;
}
I am calling alls() on onSubmit.
All other functions which are not working are similar to checkPassword().
HTML code:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data" >
<table height="100" width="1000">
<tr>
<td>
First Name<font color="#FF0000">*</font>:
</td>
<td>
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
</td>
</tr>
<tr>
<td>
Password<font color="#FF0000">*</font>:
</td>
<td>
<input type="password" name="pswd" id="pswd"/><label id="i3"></label>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
<td>
<input type="reset" name="reset" value="Reset"/>
</td>
</tr>
</table>
</form>

Considering that your CheckPassword() returns true when the password is correct.
Now in your CheckPassword() function, document.reg_indi_form.pswd.value.match(paswd) this statement returns true if the pattern matches. You have added ! means it will return true when password doesn't matches to the given pattern. I have edited the function below, also consider using boolean operators instead of using multiple/nested if statements where ever possible. You don't have any field with id i10 I think it should be i3 instead.
function CheckPassword() {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if ((document.reg_indi_form.pswd.length > 0) && (document.reg_indi_form.pswd.value.match(paswd))) {
submitFlag = true;
}
else{
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i3').style.fontSize = "12px";
}
return submitFlag;
}
And finally why are you using *= operator for boolean values in your alls() function? You should use boolean operator. Also this passes the current form or field object to the function, it is not required in this context since you are using document.formName.fieldName to access the fields of the form. Also the ternary (bool?value1:value2) operator at the end is unnecessary.
function alls() {
var valid = req()
&& validateUname()
&& CheckPassword()
&& num()
&& confirm_pswd()
&& namevalid()
&& ValidateEmail();
return valid;
}

Related

Validate form from an Array JavaScript

I'm new to JavaScript and i'm trying to create a login page and have the username and passwords or pins pull from an array. I tried my best to put it together and make it work, but I can't. Any help would be appertained. At the moment the login form is not pulling from the array. Please help.
original code:
}
var customer= ["John", "Mary", "Doe"]
var pin = [1452, 7858, 2016]
function validateusername(username) {
if (username == customer) {
return true;
}else {
return false;
}
}
function validatepassword(password) {
if (pin == pin) {
return true;
}else {
return false;
}
}
New updated code( still doesn't run)
<body>
<h1> Login to the Web ATM </h1>
<script src="js/scripts.js"></script>
<section class="loginform cf">
</section>
<form id="login" name="login" action="index_submit" onSubmit="return false" method="get" accept-charset="utf-8">
<table>
<tr>
<td> <label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" placeholder="UserName" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="password">PIN Number:</label></td>
<td><input type="password" name="password" id="password" placeholder="PIN" pattern="[0-9]{4}" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="email" name="email" id="email" placeholder="yourname#email.com" pattern="^(?=.*\..*)(?=.*#.*).*$" ><br/></td>
<td><div id="reqDisplay"></div></td>
</tr>
<tr>
<td> Empty </td>
<td><input id="emailBox" type="checkbox" name="checkbox" value="email transaction " onchange="displayReq()"/>email me a transaction confirmation</td>
<td> </td>
</tr>
<tr>
<td></td>
<td> Select an Account: <select>
<option value="account1">Checking</option>
<option value="account2">Savings</option>
<option value="account2">Money Market</option></select></td>
<td><input type="submit" value="Continue>>" onclick="validateForm()"></td>
</form>
</table>
<script type="text/javascript">
function displayReq(){
var divToReplace = document.getElementById("reqDisplay");
var chk = document.getElementById("emailBox");
var emailField = document.getElementById("email");
if (chk.checked) {
emailField.required = true;
divToReplace.innerHTML = "REQUIRED";
}else {
divToReplace.innerHTML = "";
emailField.required = false;
}
}
function validateForm(){
var myForm = document.getElementById("login");
var chk = document.getElementById("emailBox");
}
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
function validateemail(email) {
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
}else {
return false;
}
if (validateusername(myForm.username.value) && validatepassword(myForm.password.value) && (validateemail(myForm.email.value) || !chk.checked) ) {
alert("Welcome to your online ATM");
} else {
alert("Sorry the information you provided is incorrect");
}
}
</script>
You need to use different names for the global arrays and the function parameters. Otherwise, the parameter variables shadow the global variables, and you can't refer to the global variables inside the functions.
And the way to tell if something is in an array is with the indexOf() method, not ==.
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_username(username) {
return all_usernames.indexOf(username) > -1;
}
function validate_pin(pin) {
return all_pins.indexOf(pin) > -1;
}
Note that having separate functions to validate the username and PIN will not tell you if the user entered their correct PIN. For instance, if they enter username John, it won't check if they entered PIN 1452, it will allow 2016 or 7858 as well. You should use a single function to valdate both:
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
}

Can two or more conditional statements placed inside a function in javascript?

I am newbie in JavaScript. Can't find answer for this. I am not sure whether it is relevant.
I have a registration form with 2 fields.On submit, it should be validated. Here in my code, first written if condition only works. If the first if statement is commented, second if condition works.
HTML CODE :
<body>
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
</body>
JS:
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
In JSFiddle, it gives a error like
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x56b3ed0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x5c03510>, 'help_text': '', 'name': 'js_wrap'}"}
I donno what this error means!
You have to rewrite your validation code a bit.
Check demo - Demo:
Your problems:
function returns before gender is checked;
you cannot check multiple checkboxes this way: if(gender.checked)
Below is the working code
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form();">Submit</button>
</form>
</div>
When the function hits a return line, it leaves (ie returns from) the function and doesn't execute anything else in that function.
What people usually do is have a variable called valid or something similar that defaults to true. Then they have if statements that check only for things that would make the form invalid. If one of those if statements gets tripped, it handles the issue (eg telling the user that they need to fill in their gender) and sets valid to false. At the end, and only at the end, it returns valid. This way, if anything is making the form invalid, the function will return invalid, but nothing bad will happen if more than one if statement gets tripped because you can set valid to be false as many times as you want without causing any issues.
You can do it in this way.
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
var boolValidateName = validateName(name);
var boolValidateGnder = validateGnder(name);
if(boolValidateName && boolValidateGnder){
//if both are validate
}else{
//if either of or both not validate
}
}
var validateName = function (name){
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
}
var validateGender = function(gender){
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
Your return statement is not placed very well.
You can break your business login into function and call it.So,every return statement get an equal chance to run.
getElementsByName will return nodelist. You will have to iterate it to get the checked value.
Also note, return ends the current function and returns execution flow to the calling function hence any line of code after execution of return will not be executed.
Do not forget to empty('') the error messages.
Try this:
function validate_form() {
var name = document.getElementById("id1").value;
var gender = document.getElementsByName("gender");
document.getElementById("label1").innerHTML = '';
document.getElementById("label2").innerHTML = '';
var genValue = '';
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genValue = gender[i].value;
}
}
if (!name) {
document.getElementById("label1").innerHTML = "Enter Name";
return false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
return false;
} else if (!genValue) {
document.getElementById("label2").innerHTML = "Check gender";
return false;
}
return true;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td>
<label>Enter Full Name :</label>
</td>
<td>
<input type="text" id="id1" name="username" placeholder="minimum 6 charactors">
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label1"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female">
<label>Female</label>
<input type="radio" name="gender" value="male">
<label>Male</label>
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label2"></label>
</td>
</tr>
</table>
<br/>
<button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
Fiddle here
When your first block of if..else statements returns, it returns for the whole function and the if for gender never even runs. remove:
else
{
return true;
}

Javascript: Basic native form validation - can't validate more than one criterion

trying to learn how to validate form input.
The inputs need to:
1 - Not be empty.
2 - Only contain alphabetic characters (no digits).
When I test (I've only focused on first name input field for now) it will give the correct error message if I leave it blank. But, if I but digits in the field it will submit instead of displaying error message.
What am I doing wrong?
HTML:
<form id="frm1">
<fieldset id="controls">
<div>
<label for="firstname">First Name: </label>
<input type="text" id="firstname">
<span id="errFname" class="errmsg">&#42 You must enter a first name</span>
</div>
<div>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname">
</div>
<div>
<input type="submit" value="Submit">
</div>
</fieldset>
</form>
SCRIPT:
function checkForm(){
document.getElementById("frm1").onsubmit=function() {
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname)){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
return false;
} else {
return true;
}//close if
}//close function
return false;
}//close function (checkForm)
window.onload=checkForm;
The problem is that you are returning inside each if block and that is making the whole submit callback to return.
You should create a variable and return only at the end. Something like this:
function checkForm(){
document.getElementById("frm1").addEventListener("submit", function(e) {
var errors = [];
//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();
errors.push("required");
}
var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;
//check if first name has any digits
if (!alphaRegEx.test(alphafname) && errors.length === 0){
document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();
errors.push("numeric");
}
//If you want, you can do something with your errors, if not, just return
//You should rethink about handling all errors here showing/hiding messages, etc.
if (errors.length > 0) {
e.preventDefault();
return false;
}
return true;
});//close function
}//close function (checkForm)

how to correctly validate a form using javascript .?

I am trying to validate a form using javascript, Here is my code
<script type="text/javascript">
function prevSubmit(){
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var flag = 1;
if (pass1.value.length>16) {
document.getElementById("passError").innerHTML = "password may atleast 16 chars";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
if(pass1.value<=16 && pass1.value!=pass2.value)
{
document.getElementById("passError").innerHTML = "password must be same";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
return flag;
}
</script>
and here is my form element,
<form id="registration_form" action="registration.php" method="post" onsubmit="return prevSubmit();">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span id="NameError"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span id="emailError"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span id="passError"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
what I am trying to accomplish is check the password, if no match or greater than 16, then show the message and prevent submission, but its not working, Why?
Use true and false as the values of flag, not 1 and 0. You have to return false to prevent submission, anything else allows submission.
First this error message makes no sense
password may atleast 16 chars
Secondly, your second error check is wrong
if(pass1.value<=16 && pass1.value!=pass2.value)
You are saying if the value is less that the number 16 and the two values do not match.
Why would the value be less that 16? The check should just be
if (pass1.value!=pass2.value)
ANd as the others suggested, use true/false, not 1 and 0 as truthy values.
I agree with answers of Barmar and epascarello.
The if conditions should be implemented in this way:
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var ctrlError = document.getElementById("passError");
if (pass1.value.length < 16) {
ctrlError.innerHTML = "Password must be at least 16 characters long.";
return false;
}
else if (pass1.value != pass2.value) {
ctrlError.innerHTML = "Passwords do not match.";
return false;
}
else {
ctrlError.innerHTML = "";
return true;
}
just "return false" from javascript method
<input type="submit" class="button" value="sign up" onclick="javascript:return myFunc();"/>
function myFunc()
{
return false;
}
this is basic example of how to prevent submission of form, if we return false then browser/javascript engine prevent further propagation of click event and submission is prevented.

How to call two functions on a form submit

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 have multiple ways of approaching this, the easiest for your current set up would be:
combined function
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;
}
add multiple events
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 :)
Why you are creating two different functions to validate both username and passwords, by the way you can go with this too like below:
Create Another third Function in which these two have to call and check if both returns true then return true otherwise its shows message or whatever you want to do.
Here is the code by which you can do it:
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;
}
}
function finalvalidate() {
var newuser = $('[id$=newuser]').val();
var usernameresult = validateUserName(newuser);
var pwd = $('[id$=pwd]').val();
var confirmPwd = $('[id$=confirmPwd]').val();
var pwdresult = validatePassword(pwd, confirmPwd);
if (usernameresult == true && pwdresult == true) {
return true;
} else {
return false;
}
}
Hope this will work for you..
Create one function to call all your validators:
function validate() {
return validateUserName() && validatePassword();
}
HTML
<form name="NewUser" onsubmit="return validate()" action="">
Also in your password validation function you refer to incorrect field name.
Fixed code: http://jsfiddle.net/6sB29/
If you want to alert all the errors (not only the first) you can try something like this:
function validate() {
var name = validateUserName(),
pass = validatePassword();
return name && pass;
}
http://jsfiddle.net/6sB29/1/
try this
onsubmit="return fun2() && fun3();"

Categories