2013-06-26 2 views
4

Я пытаюсь выполнить эту функцию в течение двух часов, но не могу найти, где ошибка.Функция проверки достоверности формы Javascript не работает должным образом

Это ведет себя неожиданно.

Когда какое-либо поле в форме заполнено, форма отправляется в файл php, и показывает ошибки (как и ожидалось) только тогда, когда все поля остаются пустыми, то есть 5 ошибок.

Но когда заполнено любое из 6 полей, форма публикуется независимо от других ошибок в форме.

Пожалуйста, помогите мне проверить эту форму.

error - информация об ошибках, которые я покажу пользователям. errors количество найденных ошибок.

JavaScript function

function formValidator(){ 

    var elementValue = document.getElementById("first-name").value; 
    var elementName = document.getElementById("first-name"); 
    var errors = 0; 
    var error = " "; 

    if (elementValue == "" || elementValue == " " || elementValue== NULL){ 
     error = "First Name shouldn't be left empty."; 
     errors = 1; 
    } 

    var elementValue = document.getElementById("last-name").value; 
    var elementName = document.getElementById("last-name"); 

    if (elementValue == "" || elementValue == " " || elementValue== NULL){ 
     if (errors == 0){ 
      error = "Last Name shouldn't be left empty."; 
     } 
     else{ 
      error += "<br>Last Name shouldn't be left empty."; 
     } 
     errors+=1; 
    } 
    var elementValue = document.getElementById("email-for-registration").value; 
    var elementName = document.getElementById("email-for-registration"); 
    var email_err = "false"; 
    if (elementValue == "" || elementValue == " " || elementValue== NULL){ 
     email_err = "true"; 
    } 
    var elementValue = document.getElementById("phone-for-registration").value; 
    if ((elementValue == "" || elementValue == " " || elementValue== NULL) && email_err == "true"){ 
     if (errors == 0){ 
      error = "Both email and contact cannot be left empty."; 
     } 
     else{ 
      error += "<br>Both email and contact cannot be left empty."; 
     } 
     errors+=1; 
    } 
    var elementValue = document.getElementById("password-for-registration").value; 
    var elementName = document.getElementById("password-for-registration"); 
    if (elementValue == "" || elementValue == " " || elementValue== NULL){ 
     if (errors == 0){ 
      error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long."; 
     } 
     else{ 
      error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long."; 
     } 
     errors+=1; 
    } 
    else if (elementValue.length<6){ 
     if (errors == 0){ 
      error = "Password less than 6 characters aren't allowed for security reasons."; 
     } 
     else{ 
      error += "<br>Password less than 6 characters aren't allowed for security reasons."; 
     } 
     errors+=1; 
    } 
    email_err = document.getElementById("confirm-password-for-registration").value; 
    var elementName = document.getElementById("confirm-password-for-registration"); 
    if (elementValue != email_err){ 
     if (errors == 0){ 
      error = "The password to confirm doesn't match with your desired password."; 
     } 
     else{ 
      error += "<br>The password to confirm doesn't match with your desired password."; 
     } 
     errors+=1; 
    } 
    var elementValue = document.getElementById("agreed-for-registration"); 
    var elementName = document.getElementById("agreed-for-registration"); 
    if (!elementValue.checked){ 
     if (errors == 0){ 
     error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue."; 
     document.getElementById("agreed-for-registration").focus(); 
     } 
     else{ 
      error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue."; 
     } 
     errors+=1; 
    } 


    alert(errors); 

    if (errors > 1){ 
     document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>"; 
     document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>"; 
     return false; 
    } else if (errors == 1){ 
     alert(error); 
     elementName.focus(); 
     return false; 
    } else if (errors == 0){ 
     return true; 
    } 
    return false; 
} 

Функция называется здесь.

<form name="registration" class="deco_blu_form" action="<?=$base_url;?>forms/confirm-registration/members.php" method="post" onsubmit="return formValidator();"> 

Пожалуйста, спрашивайте, требуется ли какая-либо другая информация, код или пояснения.

+0

Вы получаете 'Уведомления (ошибки);'? – Sergio

+0

@ Серхио да, но, как я сказал, только когда все поля пустые, я получаю 5 ошибок. иначе ничего. –

+4

Я задаюсь вопросом, является ли тот факт, что вы используете 'NULL' вместо' null'. – RobH

ответ

3

FIDDLE

Вы должны иметь elementValue === "NULL" или elementValue == null

Я поставил console.log вместо предупреждения и onblur триггер только для меня, чтобы легче отлаживать.

Так полный код:

function formValidator() { 

var elementValue = document.getElementById("first-name").value; 
var elementName = document.getElementById("first-name"); 
var errors = 0; 
var error = " "; 

if (elementValue == "" || elementValue == " " || elementValue === "NULL") { 
    error = "First Name shouldn't be left empty."; 
    errors = 1; 
} 

var elementValue = document.getElementById("last-name").value; 
var elementName = document.getElementById("last-name"); 

if (elementValue == "" || elementValue == " " || elementValue === "NULL") { 
    if (errors == 0) { 
     error = "Last Name shouldn't be left empty."; 
    } else { 
     error += "<br>Last Name shouldn't be left empty."; 
    } 
    errors += 1; 
} 
var elementValue = document.getElementById("email-for-registration").value; 
var elementName = document.getElementById("email-for-registration"); 
var email_err = "false"; 
if (elementValue == "" || elementValue == " " || elementValue === "NULL") { 
    email_err = "true"; 
} 
var elementValue = document.getElementById("phone-for-registration").value; 
if ((elementValue == "" || elementValue == " " || elementValue === "NULL") && email_err == "true") { 
    if (errors == 0) { 
     error = "Both email and contact cannot be left empty."; 
    } else { 
     error += "<br>Both email and contact cannot be left empty."; 
    } 
    errors += 1; 
} 
var elementValue = document.getElementById("password-for-registration").value; 
var elementName = document.getElementById("password-for-registration"); 
if (elementValue == "" || elementValue == " " || elementValue === "NULL") { 
    if (errors == 0) { 
     error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long."; 
    } else { 
     error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long."; 
    } 
    errors += 1; 
} else if (elementValue.length < 6) { 
    if (errors == 0) { 
     error = "Password less than 6 characters aren't allowed for security reasons."; 
    } else { 
     error += "<br>Password less than 6 characters aren't allowed for security reasons."; 
    } 
    errors += 1; 
} 
email_err = document.getElementById("confirm-password-for-registration").value; 
var elementName = document.getElementById("confirm-password-for-registration"); 
if (elementValue != email_err) { 
    if (errors == 0) { 
     error = "The password to confirm doesn't match with your desired password."; 
    } else { 
     error += "<br>The password to confirm doesn't match with your desired password."; 
    } 
    errors += 1; 
} 
var elementValue = document.getElementById("agreed-for-registration"); 
var elementName = document.getElementById("agreed-for-registration"); 
if (!elementValue.checked) { 
    if (errors == 0) { 
     error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue."; 
     document.getElementById("agreed-for-registration").focus(); 
    } else { 
     error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue."; 
    } 
    errors += 1; 
} 


console.log(errors) 

if (errors > 1) { 
    document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>"; 
    document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>"; 
    return false; 
} else if (errors == 1) { 
    alert(error); 
    elementName.focus(); 
    return false; 
} else if (errors == 0) { 
    return true; 
} 
return false; 
} 
0

На первом, я считаю следующие поля:

  1. первого имя
  2. последнего имя
  3. электронного обмен на регистрацию
  4. телефона-для-регистрации
  5. пароль для -регистрация
  6. подтверждение-пароль для регистрации
  7. согласованный для регистрации

На всякий случай, если вы делаете что-то с абсолютным значением.

Я построил небольшой сценарий доказуемости и столкнулся с тем, что этот скрипт не работает, если у вас нет элемента с id #form_errors. Это может быть вашей проблемой? Таким образом, вызов для document.getElementById("form_errors") приведет к неопределенному, и функция не вернет false.

Такая же проверка для неопределенных элементов имеет, конечно, для других полей, тоже;)

+0

Жаль, что у меня их были. Спасибо за внимание. У меня есть решение. –