Javascript form validation not working due to typos - javascript

HTML
<form name="registerForm" action="/user/register.cgi" method="post" onsubmit="validateRegisterForm()">
<table>
<tbody>
<tr>
<td><input type="text" name="firstname" placeholder="First Name"></td>
</tr>
<tr>
<td><input type="text" name="lastname" placeholder="Last Name"></td>
</tr>
<tr>
<td><input type="email" name="email" placeholder="Email"></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Password"></td>
</tr>
<tr>
<td><input type="password" name="confirmPassword" placeholder="Confirm Password"></td>
</tr>
<tr>
<td><input type="submit" value="Register Details"></td>
</tr>
</tbody>
</table>
</form>
Javascript
function validateRegisterForm(){
var fname=document["registerForm"]["firstname"].value;
var lname=document["registerForm"]["lastname"].value;
var email=document["registerForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var pass=document["registerForm"]["password"].value;
var passlen = pass.length;
var confpass=document["registerForm"]["cofirmPassword"].value;
if (fname==null || fname=="")
{
alert("Please enter a First Name!");
return false;
}
else if (lname==null || lname=="")
{
alert("Please enter a Last Name!");
return false;
}
else if (email==null || email=="")
{
alert("Please enter a email!");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address!");
return false;
}
else if (pass==null || pass=="")
{
alert("Please enter a Password!");
return false;
}
else if (6<=passlen<=15)
{
alert("Password needs to be to have a lenght of 6-15!");
return false;
}
else if (pass!=confpass)
{
alert("Passwords do not match!");
return false;
}
}

There are some errors in your code
cofirmPassword should be confirmPassword
should be
var confpass=document["registerForm"]["confirmPassword"].value;
Instead of
var confpass=document["registerForm"]["cofirmPassword"].value;
UPDATE
Your mistakes are
x.length should be email.length
(6<=passlen<=15) should be (passlen < 6 || passlen > 15)
Your updated working DEMO

Today, in the times of HTML5, it's preferable to use the new validation mechanisms built into the browsers. A general approach is to define a constraint checking function per property (preferably in the model class in a JavaScript-based MVC app, like User.checkEmail) and assign it via HTML5's setCustomValidity function as an event listener for input events to the input field elements, so the user gets immediate validation feedback on user input, like in
emailInpEl.addEventListener("input", function () {
emailInpEl.setCustomValidity( User.checkEmail( emailInpEl.value).message);
});
So, whenever the string represented by the expression User.checkEmail(emailInpEl.value).message is empty, everything is fine. Otherwise, if it represents an error message, the browser indicates the constraint violation to the user by marking the form field concerned (typicallly with a red border) and by displaying the error message.
You can read more on using the programmatic HTNL5 validation techniques in this tutorial.

your JavaScript Code is wrong try this one
function validateRegisterForm(){
var fname=document.getElementByName["registerForm"][0].value;
var lname=document.getElementByName["registerForm"][0].value;
var email=document.getElementByName["registerForm"][0].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var pass=document.getElementByName["registerForm"][0].value;
var passlen = pass.length;
var confpass=document.getElementByName["registerForm"][0].value;
if (fname==null || fname=="")
{
alert("Please enter a First Name!");
return false;
}
else if (lname==null || lname=="")
{
alert("Please enter a Last Name!");
return false;
}
else if (email==null || email=="")
{
alert("Please enter a email!");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address!");
return false;
}
else if (pass==null || pass=="")
{
alert("Please enter a Password!");
return false;
}
else if (6<=passlen<=15)
{
alert("Password needs to be to have a lenght of 6-15!");
return false;
}
else if (pass!=confpass)
{
alert("Passwords do not match!");
return false;
}
}

Related

Javascript validation for email making issues

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.
As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now
Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.
You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.
Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Facebook Registration Plugin with RegExp

I need to validate a field in my the Facebook Registration plugin. I need to ensure that no special characters or spaces are used on the handle field. The preg_match works great with php but not sure how do do with with Javascript.
This is what I have for my if statement. Even when I used the proper text for the handle field it still comes up invalid.
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
Here is the full form code:
{"name":"name"},
{"name":"handle", "description":"Username - Letters & Underscores Only", "type":"text"},
{"name":"email"},
{"name":"country", "description":"Country", "type":"select", "options":{"United States":"United States","Canada":"Canada","Other":"Other"}},
{"name":"password"},
]'
redirect-uri="http://www.mystoragelink.com"
width="320"
onvalidate="validate">
</fb:registration>
<script>
function validate(form) {
errors = {};
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
return errors;
}
</script>
<head>
<script>
function ValidateForm()
{
var fname =document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var email= document.getElementById('email').value;
var pwd=document.getElementById('pwd').value;
//var email= document.getElementById('email');
if(email!='')
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(document.getElementById('email').value)) {
return true;
}
else
{
alert('Please provide a valid email address');
document.getElementById('email').focus();
return false;
}}
if(fname == '')
{
alert("plz enter your firstname");
return false;
}
else if(lname == '')
{
alert("plz enter your lastname");
return false;
}
else if(email == '')
{
alert("plz enter your email address");
return false;
}
// var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// else if (!filter.test(document.getElementById('email').value;))
// {
// alert('Please provide a valid email address');
// email.focus;
// return false;
//}
else if(pwd == '')
{
alert("plz enter your password");
return false;
}
}
</script>
</head>
<form action="login.php" method="POST">
<table border="1">
<tr>
<tr><td>First Name:</td><td><input type="text" name="fname" id="fname"></td></tr><br>
<tr><td>Last Name:</td><td><input type="text" name="lname" id="lname"></td></tr><br>
<tr><td> Email:</td><td><input type="text" name="email" id="email"></td></tr><br>
<tr> <td>Password:</td><td><input type="password" name="pwd" id="pwd">`enter code here`</td></tr><br>
<tr><td><input type="submit" value="Insert"onclick="return ValidateForm();"></td></tr>
</tr>
</form>
**I think this will help You**
Thanks for your efforts. I was able to find my problem.
in the var the last /i of the RegExp('^(|([a-z])|[a-z])([a-z0-9]+_?)*$/i') needed to be removed.
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Here is the working code:
var thisRegex = new RegExp("^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$");
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}

Validating PHP Form Data Using Java Script

I am validating php form data using java script, but the form send the data without validating. Am I making any mistake in creating this form validation. HTM code is:
<form name="form1" action="sendmail.php" onSubmit="return validateform1();" method="post">
<table>
<tbody>
<tr><td><input id="name" class="w200" name="name" type="text" value="Your Name" onFocus="if(this.value=='Your Name')this.value=''" onBlur="if(this.value=='')this.value='Your Name'"></td></tr>
<tr><td><input id="cname" class="w200" name="cname" type="text" value="Company Name" onFocus="if(this.value=='Company Name')this.value=''" onBlur="if(this.value=='')this.value='Company Name'"></td></tr>
<tr><td><input class="w200" name="email" type="text" value="Your Email ID" onFocus="if(this.value=='Your Email ID')this,value=''" onBlur="if(this.value=='')this.value='Your Email ID'"></td></tr>
<tr><td><input class="w200" name="mno" type="text" value="Mobile No." onFocus="if(this.value=='Mobile No.')this.value=''" onBlur="if(this.value=='')this.value='Mobile No.'"></td></tr>
<tr><td><input class="w200" name="country" type="text" value="Country" onFocus="if(this.value=='Country')this.value=''" onBlur="if(this.value=='')this.value='Country'"></td></tr>
<tr><td><textarea class="w200n h60" name="message" cols="23" rows="4" onFocus="if(this.value=='Requirements')this.value=''" onBlur="if(this.value=='')this.value='Requirements'">Requirements</textarea></td></tr>
<tr><td><input type="submit" value="Submit"><input name="reset" type="reset" value="Reset"></td></tr>
</tbody>
</table>
</form>
And the java script for this form validation is:
<script language="javascript">
function validateform1() {
if($document.form1.name.value=="") {
alert("Enter Name");
return false;
}
if($document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
if($document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
if($document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
if($document.form1.country.value=="") {
alert("Please enter country");
return false;
}
}
</script>
There's no need to use $ in "$document"
You should use "document" only
This is what you should be try:
<script language="javascript">
function validateform1()
{
if(document.form1.name.value=="")
{
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="")
{
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="")
{
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="")
{
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="")
{
alert("Please enter country");
return false;
}
else
{
return true;
}
}
</script>
and call the validateform1() on "onSubmit" event of the form.
simply do this for all fields, because you already have the value assigned for the input type as Your Name, we need to check if it is either Your name or null
if(document.form1.name.value=="Your Name" || document.form1.name.value=="")
If none of the conditions trigger and return false, you need to return true; at the end before your last closing squiggly bracket ( } ).
To clarify: I would write the function like this:
function validateform1() {
if(document.form1.name.value=="") {
alert("Enter Name");
return false;
}
else if(document.form1.cname.value=="") {
alert("Please enter company name");
return false;
}
else if(document.form1.email.value=="") {
alert("Please enter your email");
return false;
}
else if(document.form1.mno.value=="") {
alert("Please enter your mobile no.");
return false;
}
else if(document.form1.country.value=="") {
alert("Please enter country");
return false;
}
return true;
}

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

Why won't this javascript phone field form validator work?

This phone number validator doesn't work :/. Why?
Ideally, if the optional phone field is not null, it should proceed to validate the form.
The phone field is optional, and isn't required.
Validating the form:
the phone field is optional. this means that it is not required.
it should ignore comparing everything except numbers.
if the digit count is != 10 numbers, it should display the error.
if the count is equal to 10 digits, it should pass onto name.php (see the HTML)
Javascript Code:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
var regExpressionValue = /[^\d.]/g;
if (formValue !== null)
{
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}
HTML:
<form class="form" id="form" name="form" method="post" action="name.php" onsubmit="return validateForm()" />
<input type="text" name="name" id="name" />
<input type="text" name="email" id="email" />
<input type="tel" name="number" id="number" />
<button type="submit" value="Send" />Sign Up</button>
<div class="spacer"></div>
</form>
Your regular expression is wrong. Try this instead
if (/^\d{10}$/.test(formValue) === false) {
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
You have bad regexp and string presence check for phone number. Check this out:
function validateForm() {
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("Name is required.");
return false;
}
var y=document.forms["form"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Valid email required.");
return false;
}
var formValue = document.forms["form"]["number"].value;
if (formValue)
{
var regExpressionValue = /^(\d-?){10}$/g;
if (regExpressionValue.test(formValue) !== true)
{
alert("Optional phone number invalid. Example: [1234567890].");
return false;
}
}
return true;
}

Categories

Resources