Issue with validation of a form on submit? - javascript

I have a problem with my code. It is not working correctly. When you start filling the form you fill your name, then you fill phone. If you click with mouse the form is not submitted until you click somewhere else before clicking the submit button or click twice on submit button or press ENTER. Why this happens?
I want that after fill in the last field I can click mouse on submit and it will work.
//validation name
document.myform.name.onchange= function() {
var name = document.myform.name.value;
if (name === "") {
document.myform.name.removeAttribute("class", "ready");
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("Error").style.display = "block";
document.getElementById("ErrorTwo").style.display = "none";
} else {
document.myform.name.style.border = "1px solid #509d12";
document.getElementById("Error").style.display = "none";
var pattern = new RegExp("^[а-я]+$", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.name.style.border = "1px solid #da3637";
document.getElementById("ErrorTwo").style.display = "block";
document.myform.name.removeAttribute("class", "ready");
} else {
document.getElementById("ErrorTwo").style.display = "none";
document.myform.name.style.border = "1px solid #509d12";
document.myform.name.setAttribute("class", "ready");
}
}
};
//validation phone
document.myform.phone.onchange = function() {
var name = document.myform.phone.value;
if (name === "") {
document.myform.phone.removeAttribute("class", "ready");
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telError").style.display = "block";
document.getElementById("telErrorTwo").style.display = "none";
} else {
document.myform.phone.style.border = "1px solid #509d12";
document.getElementById("telError").style.display = "none";
var pattern = new RegExp("[- +()0-9]+");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telErrorTwo").style.display = "block";
} else {
document.getElementById("telErrorTwo").style.display = "none";
document.myform.phone.style.border = "1px solid #509d12";
document.myform.phone.setAttribute("class", "ready");
}
}
};
//filling the form
document.myform.onchange = function() {
var a = document.myform.name.getAttribute("class");
var c = document.myform.phone.getAttribute("class");
if (a === "ready" && c === "ready") {
document.getElementById("save").removeAttribute("disabled");
document.getElementById("save").style.cursor = "pointer";
document.getElementById("save").style.opacity = "1";
}
};
$(".callback-submit").click(function() {
var url = "send.php";
$.ajax({
type: "POST",
url: url,
data: $("#callForm form").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
$("#flipTwo").addClass("animateTwo");
}
});
return false; // avoid to execute the actual submit of the form.
});
html:
<div class="callback-form" id="callForm">
<form name='myform'>
<span class="close-btn" id="close">✖</span>
<p>Введите свои контактные данные</p>
<p>Мы Вам перезвоним</p>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<p class="Error" id="Error">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
<input type="tel" name="phone" placeholder="Телефон" maxlength="20" minlength="7">
<p class="Error" id="telError">Это поле обязательное для заполнения</p>
<p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
<div id="flipTwo">
<input class="callback-submit" type="submit" value="Отправить заявку" name="save" id="save" disabled>
<span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
</div>
<p>Данные не передаються третьим лицам</p>
</form>
</div>

I think you can make it in more organised way, First make little clean up on your html code
like: `
Введите свои контактные данные
Мы Вам перезвоним
Это поле обязательное для заполнения
Некорректный ввод
Это поле обязательное для заполнения
Некорректный ввод
<div class="group">
<div id="flipTwo">
<input class="callback-submit" type="submit" value="Отправить subtmi" name="save" id="save">
<span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
</div>
</div>
<p>Данные не передаються третьим лицам</p>
</form>`
And then write clean code for your jQuery and structured. I did partial and I hope you can complete your rest:
jQuery(document).ready(function($) {
$('#myform').on('submit', function(){
var form = this;
if(validateForm(form)) {
var values = $(form).serialize();
var url = "send.php";
$.ajax({
url: url,
type: "post",
data: values ,
success: function (data) {
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
$("#flipTwo").addClass("animateTwo");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
}
else{
event.preventDefault();
return false;
}
});
// validate Form
function validateForm(form) {
valid = true;
$(form).find('input[type=text], input[type=email]').each(function(i, val){
if(validateField(val, true) == false) { valid = false; }
});
return valid;
}
// validate all form fields
function validateField(field, submit) {
var val = $(field).val();
if(submit){
// you can more specific
if($(field).attr('name') == 'name' && val == '') {
$(field).parent().find('#Error').show();
$(field).parent().find('#ErrorTwo').hide();
return false; }
else if (!isValidName(val)){
// your next rule
return false;
}
// same way for email
if($(field).attr('type') == 'email') {
$(field).parent().addClass('error');
return false; }
else if (!isValidName(val)){
// your next rule
return false;
}
}
}
function isValidName(name) {
var pattern = new RegExp(/^[а-я]+$/);
return pattern.test(no);
}
function isValidPhone(no) {
var pattern = new RegExp(/[- +()0-9]+/);
return pattern.test(no);
}
// Run validation before Submit the form
$('input[type=text], input[type=email]').on('change', function(){
if($(this).val() != ''){
$(this).parent().removeClass('error valid');
validateField(this, false);
}
});
});
JSfiddle: https://jsfiddle.net/n32c2dwo/4/

Related

How do I get my form to use new information after errors are corrected?

I'm search but i'm not 100% how you get this to resubmit, using new information, I've got all the errors up and showing as appropriate, but in terms of, how to hit the submit button again, and then it reassesses the form; how do i go about this? Any help would be appreciated.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>RATool</title>
<link rel="stylesheet" type="text/css" href="cfcss.css">
<script src="cf.js"></script>
</head>
<body>
<h1> Health Authority </h1>
<h2> Contact Form </h2>
<form>
<fieldset>
<label for="fname">First Name:</label>
<input name="fname" id="fname" class="formfield" type="text">
<span id="errfname" class="error">*This is required</span>
<span id="errfname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errfname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="sname">Surname:</label>
<input name="sname" id="sname" class="formfield" type="text">
<span id="errsname" class="error">*This is required</span>
<span id="errsname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errsname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="title">Title: </label>
<select name="title" id="title">
<option value="Please select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss.</option>
<option value="Master.">Master.</option>
</select>
<span id="errtitle" class="error">*This is required</span>
<br>
<br>
<br>
<label for="HANo">Health Authority Number:</label>
<input name="HANo" id="HANo" class="formfield"type="text">
<span id="errHANo" class="error">*This is required</span>
<span id="errHANo2" class="error">*This must be in format ZHA123456 (ZHA followed by 6 numbers)</span>
<br>
<br>
<label for="email">Email:</label>
<input name="email" id="email" class="formfield"type="text">
<span id="erremail" class="error">*This is required</span>
<span id="erremail2" class="error">*Please enter a valid email</span>
<br>
<br>
<br>
<label for="telno">Telephone Number:</label>
<input name="telno" id="telno" class="formfield" type="text">
<span id="errtelno" class="error">* If a telephone number is entered, then it should contain only numbers, not
letters, or other disallowed characters. A valid Zedland telephone number has
11 digits (no spaces)</span>
<span id="errtelno1" class="error">*This must just be numbers</span>
<br>
<button onclick="checkForm()">Submit</button>
</fieldset>
</form>
</body>
</html>
javascript
function checkForm(){
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length > 1) {
checkFName();
e.preventDefault();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length > 1) {
checkSName();
e.preventDefault();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value.length > 0) {
if (checkHANo());
e.preventDefault();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
e.preventDefault();
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
e.preventDefault();
}
}
function checkEmail(){
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("erremail2").style.display="inline";
document.getElementById("erremail2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkHANo(){
var HANo = document.getElementById("HANo");
var hanoRegEx = /[ZHA]\d{6}/;
if (!hanoRegEx.test(HANo.value)) {
document.getElementById("errHANo2").style.display = "inline";
document.getElementById("errHANo2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkFName(){
var first = document.getElementById("fname");
var firstRegEx = /^[a-zA-Z-]{2,40}$/;
if (!firstRegEx.test(first.value)){
document.getElementById("errfname2").style.display = "inline";
document.getElementById("errfname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkSName(){
var sec = document.getElementById("sname");
var secRegEx = /^[a-zA-Z-]{2,40}$/;
if (!secRegEx.test(sec.value)){
document.getElementById("errsname2").style.display = "inline";
document.getElementById("errsname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
Your error messages are displaying by default. To hide those add the CSS class below:
.error{ display:none; }
Add this piece of code at the beginning of checkForm() to re-hide the message when error is corrected. Eg:
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
Instead of calling the formCheck() function on onclick of the button, call it onsubmit of the form with a return. Like
<form method="post" action="yourpage" onsubmit="return checkForm()">
To show all errors, declare a variable with default value as true like var isValid=true; just above/below the for loop
Eg:
function checkForm(){
var isValid = true;
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length > 1) {
isValid = checkFName();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length > 1) {
isValid = checkSName();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value.length > 0) {
isValid = checkHANo();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
isValid = false;
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
isValid = false;
}
return isValid;
}
NOTE: You have to return false from other functions such as checkEmail(),checkHANo() also if there is error. It seems you are returning only true. And remove all e.preventDefault()
That's it

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

PHP dynamic Mailchimp list

I am using mailchimp and I have different lists on mail chimp. I have a dynamic webpage using PHP and for every different link, I have created a new list. I have a database table with the list urls and I have copied a code that mailchimp provides and changed url of form onsubmit to new url and also in javascript but it does not work. It only works with url through which the code was generated.
Here is the code that mailchimp provides
<div id="mc_embed_signup">
<form action="http://worldacademy.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=175e779a1a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-NAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="NAME" class="required" id="mce-NAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_3aff75083c84f012673478808_175e779a1a" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
Javascript code
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='NAME';ftypes[1]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
Now I change this link in two location i.e. on form submit and in javacript from
http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?
to the new link which is
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
But this is not working. Any help will be much appreciated.
Thanks
I have solved this
The link in javascript needed to be changed from
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
to
http://worldtradeadvisors.us7.list-manage2.com/subscribe/post-json?u=3aff75083c84f012673478808&id=0f6cad50b6&c=?

error inner HTML on the wrong place

I have a form validation on 3 required input fields: name, address and city.
I made this javascript:
function Validate(form) {
var error_name = "";
var error_address = "";
var error_city = "";
if (form.name.value.length == 0) {
form.name.style.border = "1px solid red"; /*optioneel */
form.name.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_name = "Name cannot be left blank!";
}
if (form.address.value.length == 0) {
form.address.style.border = "1px solid red"; /*optioneel */
form.address.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_address = "Address cannot be left blank!";
}
if (form.city.value.length == 0) {
form.city.style.border = "1px solid red"; /*optioneel */
form.city.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_city = "City cannot be left blank!";
}
if (error_name.length > 0) {
document.getElementById("error_name").innerHTML = error_name ;
return false;
}
if (error_address.length > 0) {
document.getElementById("error_name").innerHTML = error_address ;
return false;
}
if (error_city.length > 0) {
document.getElementById("error_name").innerHTML = error_city ;
return false;
}
return true;
}
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
And this is a piece of the form:
<div id="form" >
<h3>Aanmelding WIES Congres</h3>
<p class="legend">Deelnemer</p>
<fieldset class="input2" id="Deelnemer">
<label>Naam:</label>
<div id="error_name"></div>
<input type="text" name="name" maxlength="25" size="25">
<label class="right">Bedrijf:</label>
<input class="right" type="text" name="company" maxlength="25" size="25">
<br/>
<label>Adres:</label>
<div id="error_address"></div>
<input type="text" name="address" maxlength="25" size="25"> <br />
<label>Postcode:</label>
<input type="text" name="postalcode" maxlength="6" size="6"> <br />
<label class="right">Plaats:</label>
<div id="error_city"></div>
<input class="right" type="text" name="city" maxlength="25" size="25">
<label>Land</label>
<select name="country">
and so on----
As you can see in the form, the name error should occur above the name field, the address error above the address field and so on..
But this is not happening: all errors are shown above the name field, wether it is name, address or city error...
What do i do wrong?
It looks like all of your errors are targeting the same div : #error_name.
Try changing each one to target the appropriate div:
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
Also, some of your input names do not match their references. For example:
form.name should be form.form_name
form.address should be form.form_address
form.city should be form.form_city
In order to display all the errors at once (instead of just one per form submission) you'll need to remove all the return false; lines and put one conditional return at the end of the function. Also, you'll need a way to "clear" the errors after the user corrects blank inputs.
Here is the restructured function:
function Validate(form) {
// INITIALIZE VARIABLES
var error_name = "";
var error_address = "";
var error_city = "";
var valid = true;
// CHECK FOR BLANK INPUTS, SET ERROR MESSAGES
if (form.form_name.value.length == 0) {
error_name += "Name cannot be left blank!";
}
if (form.form_address.value.length == 0) {
error_address += "Address cannot be left blank!";
}
if (form.form_city.value.length == 0) {
error_city += "City cannot be left blank!";
}
// UPDATE ERROR MESSAGE DISPLAYS
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
// IF ERROR MESSAGE EXISTS, CHANGE STYLES AND SET VALID TO FALSE
// ELSE IF NO ERRORS, RESET STYLES
if (error_name.length > 0) {
form.form_name.style.border = "1px solid red";
form.form_name.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_name.style.border = "none";
form.form_name.style.backgroundColor = "#FFFFFF";
}
if (error_address.length > 0) {
form.form_address.style.border = "1px solid red";
form.form_address.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_address.style.border = "none";
form.form_address.style.backgroundColor = "#FFFFFF";
}
if (error_city.length > 0) {
form.form_city.style.border = "1px solid red";
form.form_city.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_city.style.border = "none";
form.form_city.style.backgroundColor = "#FFFFFF";
}
// RETURN FORM VALIDITY (TRUE OR FALSE)
// "FALSE" STOPS THE FORM FROM SUBMITTING
return valid;
}
// CONFIGURE ONSUBMIT FUNCTION
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
Here is a working example (jsfiddle).

.focus() after submit incorrect infos to a form, doesn't work

I have an easy form. When i submit the form with incorrect informations, the error message appear but i would that the first incorrect input is highlight with focus.
I think how i use .focus() is right but it might doesn't fit with the rest of the function.
Here my code:
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" novalidate >
<div class="span-4">
<label>Email</label>
<label>Your password</label>
<label>Repeat password</label>
<label> <input class="inline check" type="checkbox" id="policy" name="policy" value="policy" /> I agree</label>
</div>
<div class="span-4">
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>"/>
<input type="password" name="pswinput" id="pswinput" value=""/>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<input type="submit" name="submit" value="Login" />
</div>
<div class="span-4">
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<p id="pswR" class="hidden">Your passwords is different</p>
<p id="checkN" class="hidden">You must agree to our term</p>
</div>
</form>
And here the script:
function validateForm(){
var email = document.getElementById("emailinput").value;
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
var check = document.getElementById("policy");
if (isValidEmail(email)){
if(isValidPsw(psw,4,8)){
if(isValidPswRep(pswrep)){
if(isValidCheckbox(check)){
return true;
}
}
}
}
return false;
}
function isValidEmail(email) {
var validCharacters = /^\w+#\w+\.\w+$/;
if(email == ""){
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "error";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return false;
email.focus();
} else if(!validCharacters.test(email)) {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "error";
return false;
email.focus();
} else {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return true;
}
}
function isValidPsw(psw, minLen, maxLen) {
var lengthPsw = psw.length;
var lettNum = /^[0-9a-zA-Z]+$/;
if(lengthPsw == 0 || lengthPsw <= minLen || lengthPsw > maxLen){
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return false;
psw.focus();
} else if(!lettNum.test(psw)){
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "error";
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
return false;
psw.focus();
} else {
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "hidden";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return true;
}
}
function isValidPswRep(pswrep){
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
if(pswrep != psw){
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "error";
return false;
pswrep.focus();
}
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "hidden";
return true;
}
function isValidCheckbox(check){
if (!check.checked){
var checkErr = document.getElementById("checkN");
checkErr.className = "error";
return false;
check.focus();
}
var checkErr = document.getElementById("checkN");
checkErr.className = "hidden";
return true;
}

Categories