I'm in the middle of coding CAPTCHA in JavaScript, and I'm trying to get the validation for a contact form to work properly. I'm almost there, the form won't be submitted until the CAPTCHA text-field is entered, but the problem is I'm still getting an error message when I entered the CAPTCHA code correctly.
<script>
function ValidateContactForm()
{
var name = document.ContactForm.name;
var phone = document.ContactForm.phone;
var code = document.ContactForm.code;
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter a valid phone number..");
phone.focus();
return false;
}
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
code.focus();
return false;
}
else {
return true;
}
return true;
}
</script>
Any help would be greatly appreciated. Thanks.
Check this lines, the problem is here:
if (code.value == "")
{
window.alert("Please enter the code as displayed on screen.");
code.focus();
return false;
}
else if (code.value != "")
{
window.alert("Your code does not match. Please try again.");
^^^^^^^^^^^^^
code.focus();
^^^^^^^^^^^^^
return false;
^^^^^^^^^^^^^
}
else {
return true;
}
This code will return false every time.
Related
i am validating a form and then asking for the confiormation through javascript…
so on submit i have called two function name validate() & make_confirm()..
onsubmit="return(validate() && show_alert(this));"
by this i am partially able to call both function but confirmation part is not working fine i have to redirect it to another page while pressing OK but its not going please help me out
validate & make_sure() function is as like:
function validate() {
if(document.getElementById('cname').value == '')
{
alert('Please enter your name');
document.getElementById('cname').focus();
return false;
}
else if(document.getElementById('address').value == '')
{
alert('Please enter your address');
document.getElementById('address').focus();
return false;
}
else if(document.getElementById('city').value == '')
{
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if(document.getElementById('state').value == '')
{
alert('Please enter your state');
document.getElementById('state').focus();
return false;
}
function make_sure() {
if(confirm("Do you really want to do this?"))
document.forms[0].submit();
else
return false;
}
Use one function for validate and confirm and set action of form to redirect form current page to another page.
function validateAndConfirm() {
if( isEmpty(id('cname').value) ) {
alert('Please enter your name');
id('cname').focus();
return false;
}
else if( isEmpty(id('address').value) ) {
alert('Please enter your address');
id('address').focus();
return false;
}
else if( isEmpty(id('city').value) ) {
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if( isEmpty(id('state').value) ) {
alert('Please enter your state');
id('state').focus();
return false;
} else {
if(confirm("Do you really want to do this?")) {
document.forms[0].submit();
}
else {
return false;
}
}
}
function isEmpty(val){
return (typeof val == 'undefined' || val === undefined || val == null || val.length <= 0) ? true : false;
}
// this function help to simplify you writing : document.getElementById to just id
function id(sid){
return document.getElementById(sid);
}
I am doing class homework about form validation and write some codes but they are not running at all. Can someone check it out what's wrong in them and fix?The first two functions are working properly. The problem is the third function formCheck for form validation does not work. If I put them in the same js document, the third function would also cause the other 2 functions to stop working. Thanks
and this is the corresponding webpage working with the javascript: http://www.acsu.buffalo.edu/~mintingt/jsvalidation.html
window.onload = function() {
document.getElementById("time").textContent = new Date();
}
function changeColor(value)
{
var color = document.body.style.backgroundColor;
switch(value)
{
case 'lightpink':
color = "#FFB6C1";
break;
case 'white':
color = "#FFFFFF";
break;
case 'plum':
color = "#DDA0DD";
break;
}
document.body.style.backgroundColor = color;
}
function formCheck()
{
var form = document.getElementById("myform");
if(form["first name"]== "") {
alert("Please fill in the required first name.");
form["first name"].focus();
return false;
}
if(form["last name"]== "") {
alert("Please fill in the required last name.");
form["last name"].focus();
return false;
}
var zip = /^\d{5}(-\d{4})?$/;
if(zip.test(form["zip code"]).value == false){
alert("Please fill in a valid zipcode.");
form["zip code"].focus();
return false;
}
var phone = /^\[0-9]{10}$|^\([0-9]{3}\)[ ]?[0-9]{3}-[0-9]{4}$/;
if(phone.test(form["phone number"]).value == false){
alert("Phone number input format is not valid.");
form["phone number"].focus();
return false;
}
var email = /^([a-zA-Z0-9_.])+#[a-zA-Z0-9]([a-zA-Z0-9])+\.([a-z])+$/;
if(email.test(form["email address"].value == false){
alert("Email format is not valid.");
form["email address"].focus();
return false;
}
form.submit();
return true;
}
You missed a parentheses ) in:
if(email.test(form["email address"].value == false){
This is the error dump:
Timestamp: 30/04/14 18:20:25
Error: SyntaxError: missing ) after condition
Source File: http://www.acsu.buffalo.edu/~mintingt/validation2.js
Line: 32, Column: 53
Source Code:
if(email.test(form["email address"].value == false){
I am trying to validate a form without using html5 validation as an exercise for a class, but I can't figure it out for the life of me.
I want to have an alert message pop up if the email and/or name is not valid/empty.
I have gotten to the point where the alert will pop up form the email OR the name field, depending which is first in the onsubmit function.
Any ideas would be greatly appreciated!
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");
if (inputEmail==="") {
alert("Please enter your email.")
return false;
} else if (!emailPattern.test(inputEmail)){
alert("Please enter a valid email address.");
return false;
} else {
return true;
};
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
alert("Please enter your name.")
return false;
} else if (!namePattern.test(inputName)){
alert("Please enter a valid name.");
return false;
} else {
return true;
};
};
You return after the first one is validated, so the second field is never checked. Instead, have a local variable that is set to true by default, and set to false of either of the fields fail validation, and return it at the end.
var valid = true;
// ...
if(inputEmail==="") {
alert("Please enter your email.");
valid = false;
// ...
return valid;
};
Maybe this doesn't work but the concept could be something like this...
document.getElementById("frmContact").onsubmit = function() {
var inputEmail= document.getElementById("email").value,
emailPattern = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"),
error = [],
i = 0;
if (inputEmail==="") {
error.push("Please enter your email");
} else if (!emailPattern.test(inputEmail)){
error.push("Please enter a valid email address.");
}
var inputName= document.getElementById("name").value,
namePattern = new RegExp("^[A-Za-z]+$");
if (inputName==="") {
error.push("Please enter your name.")
} else if (!namePattern.test(inputName)){
error.push("Please enter a valid name.");
}
if(typeof error !== 'undefined' && error.length > 0){
alert("you submit the form correctly");
} else {
for(i = 0; i < error.length; i + 1){
alert(error[i]);
}
}
};
I have the following code which works fine in desktop but in mobile device it fails. Even if the full name field is not empty, it gives the same alert.
function validateForm() {
var full_name = document.getElementById('full_name').value;
if (full_name == '') {
alert("Please enter your full name.");
return false;
}
return false;
}
Demo : http://jsfiddle.net/squidraj/yx5Mb/6/
function validateForm() {
var full_name = document.getElementById('full_name').value;
if (full_name == '') {
alert("Please enter your full name.");
return false;
}
return true;
}
If condition fails you are not returning true.
I have this email form validation script:
<script type="text/javascript" language="javascript">
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
}</script>
Can someone please tell me what do I have to add in this script in order to make the users enter a valid email address. Also I would like in the rest of the fields to make users to enter text (not links).
I've tried to add different pieces of code which I found on different websites but they did not work and this is because I am not sure if I am adding them right.
Thank you for reading my request.
All the best,
Andi
For e-mail checking you can use following code in else part after checking if e-mail is empty
function validateForm(){
var email = document.getElementById("email").value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
and for url with same logic you can use following regular expression
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
following is a working example based on your work, you can improve this code it is only for showing you how it should be.
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
else{
var name = thisform.Name.value;
if (!checkURL(name)) {
alert("name cannot be a url");
return false;
}
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
else{
var email = thisform.Email.value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
else{
if (!checkURL(thisform.Subject.value)) {
alert("subject cannot contain a url");
return false;
}
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
else{
if (!checkURL(thisform.Message.value)) {
alert("message cannot contain a url");
return false;
}
}
}
function checkURL(url){
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
if (url.search(urlRegEx) == -1) {
return true;
}
return false;
}
See this post for regex urls: regular expression for url
See this post for email validation: Validate email address in JavaScript?
See this for X browser event listening, if would use jQuery, ie8 uses attach see this: Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
I would recommend looping through the form inputs, and checking if its email and if its not run the regex against the link.
(function(){
var validateForm = function(form){
var errors = [], inputs = form.getElementsByTagName('input');
for(var input = 0; input<inputs.length; input++){
var currentInput = inputs[input];
if(currentInput.value === ''){
// handle attributes here for error message, push error message
if(currentInput.attribute('name') === 'email'){
// handle email
// push error message
}
}
}
return errors;
}
var contactForm = document.getElementById('contact');
contactForm.addEventListener('submit', function(e){
var errorMessages = validateForm(contactForm);
if(errorMessages.length === 0){
} else {
e.preventDefault() // stop the form from submitting
// handle your messages
}
}
}());