Answer the question
In order to leave comments, you need to log in
Validation for the form without reloading the page, how to enable captcha verification?
Hello, I implemented it for a long time with the help of knowledgeable people in the js code, did the validation, put it in the admin panel, there is no captcha, I also decided to put this validation method on the comments.
There is a problem, how to add to the validation that the captcha would be checked ???
Site on Kohana 3.1 framework, validation with page reload disabled. decided to do it through js.
This method works like this, when you click on submit, the form is checked, then the js script is thrown into the validation by id where it is displayed, I have it through the scroll. you can see it in the script.
<!-- валидация для формы -->
<script type='text/javascript'>
function checkForm(obj, elems) {
var element, pattern;
for (var i = 0; i < obj.elements.length; i++) {// пробегаемся по всем элементам формы
element = obj.elements[i];
// Проверяем только нужные поля
if (elems != undefined)
if (elems.join().indexOf(element.type) < 0) continue;
// И только если есть чего говорить юзеру в случае ошибки
if (!element.getAttribute("check_message")) continue;
if (pattern = element.getAttribute("check_pattern")) { // если задан рег
pattern = new RegExp(pattern, "g");
if (!pattern.test(element.value)) {
document.getElementById('validationka').style.display = "block"
document.getElementById('validationka').innerHTML =element.getAttribute("check_message");
<!-- при нажатии на кнопку добавить, срабатывает валидация и перекидывает к валидации -->
window.scrollTo(0, 50);
element.focus();
return false;
}
} else if(/^\s*$/.test(element.value)) {// иначе просто проверка что поле не пустое
document.getElementById('validationka').style.display = "block"
document.getElementById('validationka').innerHTML = element.getAttribute("check_message");
<!-- при нажатии на кнопку добавить, срабатывает валидация и перекидывает к валидации -->
window.scrollTo(0, 50);
element.focus();
return false;
}
}
return true;
}
</script>
<form method="post" onSubmit="return checkForm(this)" id="addcom" action="/main/send">
<input type=text id="name" name="name" check_message="Введите имя, поле обязательно для заполнения" value="<?=$data['name']?>">
<input type=text id="email" name="email" check_message="Введите Email, поле обязательно для заполнения" value="<?=$data['email']?>">
<textarea name="comment" check_message="Введите текс комментария, поле обязательно для заполнения" rows="3"><?=$data['comment']?></textarea>
<div class="fullnewscapcha"><?=$captcha;?></div>
<input type="text" placeholder="Сюда" name="captcha" id="captcha">
<button type="submit" name="submit" id="submit" class="btn btn-primary">Добавить комментарий</button>
</form>
<div id="validationka"></div>
// комментарий к новостям
public function action_send()
{
$uri = $this->request->referrer() != NULL ? $this->request->referrer() : '';
$data = $_POST;
if (Captcha::valid($data['captcha']))
{
ORM::factory('Review')->values($data)->create();
Session::instance()->set('message', array(
'class' => 'success',
'text' => 'Ваш комментарий будет добавлен после проверки'
));
Session::instance()->delete('data');
}
else
{
Session::instance()->set('message', array(
'class' => 'danger',
'text' => 'Не правильно ввели код с картинки'
));
Session::instance()->set('data', $data);
}
$this->request->redirect($uri);
}
Answer the question
In order to leave comments, you need to log in
Captcha can only be checked with a separate ajax request to the server. Study your captcha, look at its API.
1. Return the action in which the validation and saving of the comment took place (with a page reload). It will check both the data of the comment itself and the captcha.
2. Add a check for is_ajax(), depending on the result, send a redirect or a view HTML code (for non-Ajax requests), or JSON or something else (you can look at the headers, you can not worry and always give json). The json will contain the result of the operation ('result' => true, for example) and a list of validation errors ('errors' => {'field' : 'error', ...}. If the save is successful, then return the comment id or something else, depending on what you plan to do in case of success
3. When submitting the form, send an ajax request with data (+ captcha) If there are errors (look at result, errors, etc.),
Accordingly, for users with disabled js, adding comments works with a page reload, and for the rest there is ajax. At the same time, the action is one for all.
In any case, never rely on ClientSide validation alone. On ServerSide (that is, in PHP), in any case, all these checks will need to be done.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question