Validation using java script - javascript

I am trying to give validation to both fields email and name but only email is getting validated and its not checking for name field. I am not able to find what is wrong in the code.
<html>
<body>
<form name="myForm">
Email: <input type="text" name="email" id="email2">
<br>
Name: <input type="text" name=" fname">
<button type="submit" name="submit" onclick="validateForm()">submit</button>
<br> email
<div id="email1"></div>
</form>
</body>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var email1 = document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
return false;
}
}
</script>
</html>

<input type="text" name=" fname">
There is a space before fname.That is why it is not working.You can try simple solution like this

You have missed giving id to Name: <input type="text" name=" fname"> Assign ID to Name: <input type="text" name=" fname" id="fname">.
As document.forms["myForm"]["fname"].value; this requires element id to fetch value.

Add an additional boolean to check your validation
function validateForm() {
var x = document.forms["myForm"]["email"].value;
//Additional boolean
var success = true;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
success = false;
}
var email1= document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
success = false;
}
return success;
}

Related

Allow only a list of email to submit request using form javascript validation

I have a list of valid user. I want that only these user will be able to send post request all other user should be identified as invalid user. I have written javascript code but unable to make invalid user to stop the execution of programs.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
for (i=0; i< eMailList.length; i++){
if(x != eMailList[i]){
alert("Not a valid user");
return false;
}
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
At first if you care about security issues, you shouldnt do it on the javascript side.
See code sample below:
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
var i;
if($.inArray(x,eMailList) == -1)
{
alert("Not a valid user");
}
else
{
alert("valid user");
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Link to JsFiddle
There is no need to loop through the array you can just use if(eMailList.indexOf(x) < 0) implemented below. The reason your code would always returns false is because that even if you enter a valid email it is not equal to every other item in the array.
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
var eMailList = ["hankev#gmail.com", "slurp#gmail.com", "cofo#gmail.com", "vecrify#gmail.com"];
if(eMailList.indexOf(x) < 0){
alert("Not a valid user");
return false;
}
}
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

First check for errors before submitting

I have a form which I want it to be verified and validated by a try-catch block plus two other functions.
Here is what I have:
HTML:
<h5>Please enter your name below</h5>
<form name="textForm">
<label for="name">First name:</label>
<input type="text" name="fname" id="name">
</form>
<h5>Please enter your e-mail below</h5>
<form name="mailForm">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
</form>
<form action="">
<label for="height">Your height:</label>
<input type="text" placeholder="in centimetres" name="personHeight" id="height" />
<br></br>
<input formaction="mailto:test#gmail.com" onclick="heightCheck();validateTextForm();validateMailForm();" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
<br></br>
<p id="mess"></p>
</form>
JS:
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value; 
if (x == "")   
throw "enter your height"; 
if (isNaN(x)) throw "not a number";
if (x > 250)    
throw "height is too high";
if (x < 80)     
throw "height is too low"; 
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + "."; 
}
}
The thing that i want it to happen is the following: Firstly, it does the form validation but afterwards if its correct, submits as well.
I tried to make it first verify the forms before actually submits but without any success.
While browsing i find out it could be done by either stopPropaganation, preventDefault or return false methods but still have no idea how to make it happen.
I will rep the guys who help me. Thanks in advance!
Fiddle: However in fiddle it doesn't run properly as it should: http://jsfiddle.net/5T9sJ/
You need to change your code according to my editions:
...
<input formaction="mailto:test#gmail.com" type="submit" value="Submit all" id="submit" method="post" formtarget="_blank" />
...
Then make processValidate method to wrap all other validations into it:
$(document).ready(function () {
$('input#submit').click(function (e) {
e.preventDefault();
validateTextForm();
validateMailForm();
heightCheck();
});
function validateTextForm() {
var x = document.forms["textForm"]["fname"].value;
if (x === null || x === "") {
alert("First name must be filled out");
return false;
}
}
function validateMailForm() {
var z = document.forms["mailForm"]["email"].value;
var atpos = z.indexOf("#");
var dotpos = z.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= z.length) {
alert("Not a valid e-mail address");
return false;
}
}
function heightCheck() {
try {
var x = document.getElementById("height").value;
if (x === "") throw "enter your height";
if (isNaN(x)) throw "not a number";
if (x > 250) throw "height is too high";
if (x < 80) throw "height is too low";
} catch (err) {
var y = document.getElementById("mess");
y.innerHTML = "Error: " + err + ".";
}
}
});
Explanation:
You have several methods bound on submit input type, so clicking on it will always call form submission.
I added jQuery click handler for this action to prevent the default action of submit button.
I think e.preventDefault() suits here the best.
WORKING DEMO: http://jsfiddle.net/rbegf/

onsubmit not fired when last entry is correct

Everything works fine when there is nothing in the email input, but as soon as I enter a "valid" email address, it doesn't even fire the function because the alert is never triggered. Any help will be appreciated.
Javascript (js/registration.js):
function validateForm() {
var value1 = document.forms["regForm"]["username"].value;
var value2 = document.forms["regForm"]["pass1"].value;
var value3 = document.forms["regForm"]["pass2"].value;
var value4 = document.forms["regForm"]["email"].value;
var atpos = value4.indexOf("#");
var dotpos = value4.lastIndexOf(".");
var check = true;
if(value1 == null || value1 == "") {
$("#userCheck").html("<img src='images/ico_fail.png'/> Please enter a user name! (25 character limit)");
check = false;
} else $("#userCheck").html("<img src='images/ico_pass.png'/>");
if(value2 == null || value2 == "") {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Please enter a password! (25 character limit)");
check = false;
} else {
if(value2.length < 8) {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Password must be 8 to 25 characters");
check = false;
} else $("#pass1Check").html("<img src='images/ico_pass.png'/>");
}
if(value3 == null || value3 == "") {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Please re-enter your password! (25 character limit)");
check = false;
} else {
if(value3 != value2) {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Password does not match!");
check = false;
} else $("#pass2Check").html("<img src='images/ico_pass.png'/>");
}
if(value4 == null || value4 == "") {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else {
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else $("#emailCheck").html("<img src='images/ico_pass.png'/>");
}
alert(check);
return check;
}
HTML:
<form name="regForm" method="post" action="" onsubmit="return validateForm();">
<input type="text" id="uName" name="username" size="25" maxlength="25" value=""/>
<span id="userCheck"> (25 character limit)</span></br>
<input type="password" id="password1" name="pass1" size="25" maxlength="25" value=""/>
<span id="pass1Check"> (25 character limit)</span></br>
<input type="password" id="password2" name="pass2" size="25" maxlength="25" value=""/>
<span id="pass2Check"></span></br>
<input type="text" name="email" size="25" value="" />
<span id="emailCheck"></span></br>
<input type="submit" name="submit" value="Register" />
<input type="hidden" name="perm" value="3" /> <!-- regular user -->
<input type="hidden" name="redirect" value="index.php" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
You dont have x defined here. i think it should be value4.length
The problem is: ReferenceError: x is not defined
At this line:
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {

Form posts even when I detect an error in a field

I use javascript to validate a form before to submit. When I detect an error on a field the form still posts. How can I prevent from submitting on error?
Here's my form:
<form onSubmit="return validateForm()" action="send.php" method="post" name="formulaire">
Prénom: <input type="text" name="prenom"><p id="valider_prenom"></p><br>
Nom: <input type="text" name="nom"><p id="valider_nom"></p><br>
Email: <input type="text" name="email"><p id="valider_email"></p><br>
Code postal: <input type="text" name="codepostal"><p id="valider_codepostal"></p><br>
<INPUT type="submit" value="Envoyer">
</form>
Here's my javascript function:
<script type="text/javascript">
function validateForm()
{
var prenom = document.forms["formulaire"]["prenom"].value;
var nom = document.forms["formulaire"]["nom"].value;
var email = document.forms["formulaire"]["email"].value;
var codepostal = document.forms["formulaire"]["codepostal"].value;
var erreur = false;
// Pour la validation du format de email
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (prenom == null || prenom == "")
{
document.getElementById('valider_prenom').innerHTML = '* Requis';
erreur = true;
}
if (nom == null || nom == "")
{
document.getElementById('valider_nom').innerHTML = '* Requis';
erreur = true;
}
if (email == null || email == "")
{
document.getElementById('valider_email').innerHTML = '* Requis';
erreur = true;
}
else if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length)
{
document.getElementById('valider_email').innerHTML = '* Adresse incorrect';
erreur = true;
}
if (codepostal == null || codepostal == "")
{
document.getElementById('valider_codepotal').innerHTML = '* Requis';
erreur = true;
}
if (erreur){return false;}
}
</script>
If you replace the last line of your code with if (erreur == true){return false;}
it will validate your form.

How do I check to make sure form fields are not empty strings?

I am trying to get my validateForm() method to make sure email is valid (which I have done) and also make sure the 'name' and 'comments' fields are not empty. For some reason I cannot get the second part down, and need some assistance. Here is the current code I have.
<script type="text/javascript">
<!--
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var x = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
}
if (x == null || x == "") {
alert("Empty Fields");
return false;
}
}
// -->
</script>
And the form:
<form name="myForm" action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return validateForm()" method="POST">
Your name: <br>
<input type="text" name="name" ><br>
<br>
Your email: <br>
<input type="text" name="email"><br>
<br>
Your comments: <br>
<textarea name="comments" rows="15" cols="50"></textarea><br><br>
<input type="submit" value="Submit">
</form>
Why are you using same variable for both field name and email. It doesn't make sense.
There is one more syntax error in your code i.e. You have put an extra } before checking second condition. So it makes that condition outside of that function
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
}
So here is JS Fiddle Example
You are assigning both the form fields to the variable x
You should opt below points to keep in mind for above code
(1) validation for Empty fields should come first then Email checking.
(2) As per the code, your Empty field logic is not a part of validateForm() (It might be typo),so when validationForm() method will called,this logic won't execute
(3) you should write return true at the end of method validateForm()
(4) Use different variable names of field checking
GO through above points,it will be helpful to solve your Issue. :)
First there are syntax error in your code. It seems that there are two redunant curly braces. And then you assign both the two fields to x, and only the name field get its value. Also, you'd better first check the email field empty or not and then operate on it. Finally I don't think your check for email is right. For example: xxx#a.info. So you may try:
function checkEmail(aEmail){
var pattern=//w+([-+.']/w+)*#/w+([-.]/w+)*/./w+([-.]/w+)*/;
var objExp=new RegExp(pattern);
if(objExp.test(str)==true){
return true;
}else{
return false;
}
}
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["name"].value;
if (x == "" || y == "") {
alert("Empty Fields");
return false;
}
if (!checkEmail(y)) {
alert("Not a valid email");
return false;
}
}
You should try this way:
function validateForm(){
var x=document.forms["myForm"].getElementsByName('email').value;
var y=document.forms["myForm"].getElementsByName('name').value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
alert("Not a valid e-mail address");
return false;
}
if (y==null || y==""){
alert("Empty Fields");
return false;
}
}

Categories