2016-08-23 8 views
0

У меня есть вопрос к вопросу.Подтвердить форму перед отправкой php

У меня есть форму, которую пользователь должен заполнить. Есть несколько полей, которые имеют ограничения (например, имя не может быть пустым). Проблема в том, что каждый раз, когда я нажимаю кнопку отправки, я получаю всплывающее сообщение о том, что имя не может быть пустым, но оно автоматически перенаправляется на другую страницу. Поэтому возникает вопрос: как я могу изменить свой код, чтобы выполнить проверку, прежде чем перенаправлять на страницу, или, если пользователь нажимает кнопку снаружи или нажимает вкладку?

Для того, чтобы достичь этого, я использую PHP, контактную форму 7 и wordpress. Вот мой код:

функция PHP createAccount.php

<?php 
require_once('../../../wp-load.php'); 
include ('../../../wp-config.php'); 
global $wpdb;  
$nameErr = ""; 
if(isset($_POST['next'])) 
{ 
$name=addslashes($_POST['cName']); 
$surname=addslashes($_POST['cSurname']); 
$email=addslashes($_POST['cEmail']); 
$phone =addslashes($_POST['cPhone']); 
$otherPhone=implode($_POST['cOtherPhone']); 
$languages=implode(' | ', $_POST['cLanguages']); 
$address=addslashes($_POST['cAddress']); 
$neighborhood=$_POST['cNeighborhood']; 
$pswd=addslashes($_POST['cPswd']); 
$service=$_POST['cService']; 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    if(empty($_POST["cName"])) { 
     $message = "wrong answer"; 
    echo "<script type='text/javascript'>alert('$message'); 
    </script>"; 
} 
}else{ 

$wpdb->insert("Client",array(
"cName"=>$name, 
"cSurname"=>$surname, 
"cEmail"=>$email, 
"cPhone"=>$phone, 
"cOtherPhone"=>$otherPhone, 
"cLanguages"=>$languages, 
"cAddress"=>$address, 
"cNeighborhood"=>$neighborhood, 
"cPswd"=>$pswd, 
"cService"=>$service 
)); 
print_r("uq"); 
} 
} 
$wpdb->show_errors(); 
?> 

Контактная форма 7 страница

<form action="/wp-content/plugins/my-codes/signUp.php" method="post"> 
[contact-form-7 id="422" title="Member Signup"] 
</form> 

Контактный формуляр

<p>Your Name (required)<br /> </p> 
[text* cName id:cName] 

<p>Your Surname (required)<br /> </p> 
[text* cSurname id:cSurname] 

<p>Your Email (required)<br /></p> 
[email* cEmail id:cEmail] 

<label> Your Telephone Number (required) 
[tel* cPhone id:cPhone tel-106 placeholder "123 456 789"] </label> 

<label> Other Telephone Number (required) 
[tel* cOtherPhone id:cOtherPhone tel-106 placeholder "123 456 789"] </label> 

<h3>What languages do your prefer?</h3> 
<input id=cLanguages type="checkbox" name=cLanguages[] value="English"> 
<use_label_element for="check_14">English</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="Hebrew"> 
<use_label_element for="check_15">Hebrew</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="French"> 
<use_label_element for="check_16">French</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="Spanish"> 
<use_label_element for="check_17">Spanish</use_label_element> 

<p>Your Address (required)<br /> </p> 
[text* cAddress id:cAddress] 

<select cNeighborhood id:cNeighborhood name=cNeighborhood> 
<option value="Bat Yam">Bat Yam</option> 
<option value="Raanana">Raanana</option> 
</select> 

<label> Create Password (required) 
[text* cPswd id:cPswd] </label> 

<label> Confirm Password (required) 
[text* cPswd id:cPswd] </label> 

<label> Pick a Service (required)</label> 
<select cService id:cService name=cService> 
<option value="Babysitter">Babysitter</option> 
<option value="Cleaner">Cleaner</option> 
</select> 

<input type="submit" name="next"> 

Любая помощь пожалуйста? благодаря!

UPDATE КОНТАКТ ФОРМА

<form id="commentForm" action="/wp-content/plugins/my-   codes/createAccount.php" method="post"> 
<p>Your Name (required)<br /> </p> 
[text* cName id:cName] 

<p>Your Surname (required)<br /> </p> 
[text* cSurname id:cSurname] 

<p>Your Email (required)<br /></p> 
[email* cEmail id:cEmail] 

<label> Your Telephone Number (required) 
[tel* cPhone id:cPhone tel-106 placeholder "123 456 789"] </label> 
<label> Other Telephone Number (required) 
[tel* cOtherPhone id:cOtherPhone tel-106 placeholder "123 456 789"] </label> 

<h3>What languages do your prefer?</h3> 
<input id=cLanguages type="checkbox" name=cLanguages[] value="English"> 
<use_label_element for="check_14">English</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="Hebrew"> 
<use_label_element for="check_15">Hebrew</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="French"> 
<use_label_element for="check_16">French</use_label_element> 

<input id=cLanguages type="checkbox" name=cLanguages[] value="Spanish"> 
<use_label_element for="check_17">Spanish</use_label_element> 

<p>Your Address (required)<br /> </p> 
[text* cAddress id:cAddress] 

<select cNeighborhood id:cNeighborhood name=cNeighborhood> 
<option value="Bat Yam">Bat Yam</option> 
<option value="Raanana">Raanana</option> 
</select> 

<label> Create Password (required) 
[text* cPswd id:cPswd] </label> 

<label> Confirm Password (required) 
[text* cPswd id:cPswd] </label> 

<label> Pick a Service (required)</label> 
<select cService id:cService name=cService> 
<option value="Babysitter">Babysitter</option> 
<option value="Cleaner">Cleaner</option> 
</select> 

<input type="submit" name="submit" value="Submit"> 
</form> 
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"> </script> 
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script> 
<script> 
$("#commentForm").validate(); 
</script> 

Я хочу быть перенаправлены на

/wp-content/plugins/my-codes/createAccount.php

при нажатии кнопки отправки.

+0

Вы хотите использовать валидацию на стороне клиента ион? –

+0

Я думаю, что лучший вариант нет? – AlguienEnEsteMundo

+0

Существует два типа проверки: 1. Сторона клиента 2. Серверная сторона. какой вам нужен? –

ответ

0

В <input id=cLanguages type="checkbox" name=cLanguages[] value="English">, например, вы можете добавить необходимый атрибут как так:

<input id=cLanguages type="checkbox" name=cLanguages[] value="English" required> 

Существует автоматическая проверка для требуемых полей в HTML, он доступен для всех типов ввода.

+0

И тогда у меня должно быть автоматическое сообщение?говоря, что это необходимый файл? – AlguienEnEsteMundo

+0

Точно также вы можете создать свою собственную проверку с помощью javascript. –

1

В этом случае вы можете использовать клиент на стороне JQuery проверки:

Jquery Validation

$('#form_id').validate({ 
    rules: 
    { 
     elem_name: 
     { 
      required: true 
     } 
    }, 
    messages: 
    { 
     elem_name: 
     { 
      required: "Mandatory field" 
     } 
    } 
}); 
+0

Я понимаю. Но затем, когда я нажимаю кнопку для отправки, ничего не происходит. – AlguienEnEsteMundo

+0

проверить консоль, если есть ошибка? –

+0

Теперь я проверяю. Uodate мой ответ в середине – AlguienEnEsteMundo

1

вы можете использовать JQuery Validation подключаемый модуль для проверки и формы представления

вы можете задать пользовательские сообщения, а

// Setup form validation on the #register-form element 
$("#register-form").validate({ 

    // Specify the validation rules 
    rules: { 
     firstname: "required", 
     lastname: "required", 
     email: { 
      required: true, 
      email: true 
     }, 
     password: { 
      required: true, 
      minlength: 5 
     }, 
     agree: "required" 
    }, 

    // Specify the validation error messages 
    messages: { 
     firstname: "Please enter your first name", 
     lastname: "Please enter your last name", 
     password: { 
      required: "Please provide a password", 
      minlength: "Your password must be at least 5 characters long" 
     }, 
     email: "Please enter a valid email address", 
     agree: "Please accept our policy" 
    }, 

    submitHandler: function(form) { 
     form.submit(); 
    } 
}); 
+0

. Должен ли я добавить этот код в форму контакта? Ведь все поля или правильный путь делают это отдельно? – AlguienEnEsteMundo

+0

Не работает. Когда я нажимаю кнопку, ничего не происходит .. любые идеи? Ошибок в консоли нет. – AlguienEnEsteMundo

Смежные вопросы