hey guys i was working on a contact form for my college and i want to validate the contact form but it doesnt seem to be working! can anyone help me on this!
here is my code:
<script type="text/javascript" language="javascript">
function validateMyForm ( ) {
var isValid = true;
var name = document.getElementsByName("Name");
var email = document.getElementsByName("Email");
var phone = document.getElementsByName("Phone");
if ( name == "" ) {
alert ( "Please enter your Name" );
isValid = false;
} else if ( email == "" ) {
alert ( "Please enter your Email ID" );
isValid = false;
} else if ( phone == "" ) {
alert ( "Please enter your Phone Number" );
isValid = false;
}
return isValid;
}
</script>
Body part:
<h3>Contact form:</h3>
<form id="contact-form" method="post">
<fieldset>
<label class="name">
<font color='black'><b><span>Name:</span></b></font><input type="text" id="Name" name="Name"></label>
<label class="email">
<font color='black'><b><span>Email ID:</span></b></font><input type="email" id="Email" name="Email"></label>
<label class="phone"><font color='black'><b><span>Phone:</span></b></font><input type="text" id="Phone" name="Phone"></label>
<label class="message">
<font color='black'><b><span>Queries:</span></b></font><textarea></textarea></label><br><br>
<div class="btns">
<button id="submit" name="submit" onclick="javascript:return validateMyForm();">Send</button>  
<button onClick="document.getElementById('contact-form').reset()">Clear</button>
</div>
</fieldset>
</form>
var name = document.getElementsByName("Name");
That gets a list of elements with name of "name".
var name = document.getElementsByName("Name")[0].value;
That gets the first of the elements with name of "name", then gets the value. You should change all 3 of them.
If you want to have it go by the id, not the name, you can use:
var name = document.getElementById("Name").value;
If you want it to go by name, but not the first in the page, rather the first in the form, use this:
var name = document.getElementById('contact-form').getElementsByName("Name")[0].value;
Related
I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.
I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}
basically i have this form. when i press "send message" button, if there is a field with no value in it, the field comes back with a red error message in it. but when i press reset, it does not change the values to black text, and the text stays red.. how do i fix this?
<form id="contact" action="" onsubmit="checkContactForm( this ); return false;">
<p>Fill in the form below to send me a message!</p>
<p>
<label for="firstname">First name:</label>
<input name="firstname" id="firstname" onfocus="resetField( this );" />
</p>
<p>
<label for="lastname">Last name:</label>
<input name="lastname" id="lastname" onfocus="resetField( this );" />
</p>
<p>
<label for="email">E-mail address:</label>
<input name="email" id="email" onfocus="resetField( this );" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" onfocus="resetField( this );"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
</form>
and this javascript:
var requiredFields = [ "firstname", "lastname", "email", "message" ];
function checkContactForm( theForm ) {
for ( i in requiredFields ) {
var fieldName = requiredFields[ i ];
var theField = theForm[ fieldName ];
if ( !theField.value || theField.value == "Error" ) {
theField.style.color = "#f66";
theField.value = "Error";
var emptyFields = true;
}
}
if ( !emptyFields ) {
theForm.submit();
}
}
function resetField( theField ) {
if ( theField.value == "Error" ) {
theField.value = "";
theField.style.color = "#000";
}
}
Resetting a form only resets the values, so you need to add a listener to the reset button to change the colour back, e.g.
<input type="reset" onclick="resetForm(this);">
and in the function something like:
function resetForm(el) {
var form = el.form;
for (var els = form.elements, i=els.length; i; ) {
els[--i].style.color = #000000;
}
}
The above is just an example, you'll need to tailor it to suit.
Also, it's not a good idea to use for..in over an array. Where you have:
for ( i in requiredFields ) {
you are better off to do something like:
var requiredFields = {'firstname':'', 'lastname':'', 'email':'', 'message':''};
var element, elements = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++) {
element = elements[i];
if (element in requiredFields) {
if (!element.value || element.value == 'Error') {
...
Also, if the form controls have a name, they rarely need an ID as well.
I am having issues using getElementById in a form. I have tried several ways with no luck. I basically need the form to verify that both First Name and Last Name fields are filled in, and display a popup box with the names displayed.
Below is the code I have tried. I tried 2 different ways in my javascript and I am not sure what I am missing.
<form name="form" id="form" method="post" action="">
<p class="FirstName">
<label for="FirstName">First Name:</label>
</p>
<p>
<input name="FirstName" type="text" id="FirstName" />
</p>
<p class="LastName">
<label for="LastName">Last Name:</label></p>
<p>
<input name="LastName" type="text" id="LastName" />
</p>
<p class="submit">
<input name="getName" type="button" id="getName" value="Get Name" onClick=”getName();" />
</p>
</form>
var getName = function () {
if (document.getElementById("FirstName").value == "" || document.getElementById("LastName").value == "") {
return ("Please enter a first name and a last name.");
} else {
var FullName = document.getElementById("FirstName").value + ' ' + document.getElementById("LastName").value;
return FullName;
}
}
function getName() {
var FullName = document.getElementById('FirstName');
document.getElementById('LastName');
if (FullName.value != "")
alert(FullName.value)
else
alert("Please enter first and last name")
}
The first way you tried was the right one.
The problem is, you're not binding the onclick event to a function.
You declare the getName function in the head tag, interpreted before the body tag.
But you overwrite getName when declaring the button input with its id and name set to getName.
You can just change its id and name to submitButton for example. You could also move the function declaration to the end of the body tag, or wrap it in an onLoad method.
I wrapped the getName call in an alert to see the result (alert(getName()))
Check out the jsFiddle : http://jsfiddle.net/zpNSv/1/
<form name="form" id="form" method="post" action="">
<p class="FirstName">
<label for="FirstName">First Name:</label>
</p>
<p>
<input name="FirstName" type="text" id="FirstName" />
</p>
<p class="LastName">
<label for="LastName">Last Name:</label>
</p>
<p>
<input name="LastName" type="text" id="LastName" />
</p>
<p class="submit">
<input name="submitButton" type="button" id="submitButton" value="Get Name" onClick="alert(getName())" />
</p>
</form>
AND JS
function getName() {
var FirstName = document.getElementById("FirstName"),
LastName = document.getElementById("FirstName");
if (FirstName.value == "" || document.getElementById("LastName").value == "")
{
return ("Please enter a first name and a last name.");
}
else
{
var FullName = FirstName.value + ' ' + LastName.value;
return FullName;
}
}
Take a closer look at this line, you are doing nothing with the last statement
var FullName = document.getElementById('FirstName'); document.getElementById('LastName');
You have 2 getName. only one can live.
function getName(){
var firstName = document.getElementById("firstName").value;
var lastName= document.getElementById("lastName").value;
if(firstName === "" || lastName === ""){
alert("You need to fullfield both First Name and Last Name");
}
}else{alert("This work.");}