Как сделать проверку полей формы с помощью JQuery в FormIt

Проверка полей в MODX Revolution с использованием FormIt и jQuery.

  • Если у вас не установлен FormIt, пожалуйста, скачайте и установите.
  • Не забывайте зарузить последнюю версию jQuery.

Отлично давайте начнём, вначале нужно вызвать наш сниппет FormIt:

Код
[[!FormIt? &hooks=`email,redirect` &emailTpl=`contactFormTpl` &emailFrom=`[email protected]` &emailFromName=`Your Site Name` &emailSubject=`Message From Your Site Name` &emailTo=`[email protected]` &redirectTo=`36` &validate=`name:required, email:email:required, comments:required:stripTags` ]]

Чанк вывода контакт формы contactFormTpl:

Код
<p>Name: [[+name]]</p> <p>Email: [[+email]]</p> <p>Phone: [[+phone]]</p> <p>Budget: [[+budget]]</p> <p>Comments: [[+comments]]</p>

Добавим нашу форму:

Код
<form id="contactForm" action="[[~[[*id]]]]" method="post"> <fieldset> <label for="name">Your Name* [[!+fi.error.name]]</label> <input type="text" name="name" id="name" value="First and last name[[!+fi.name]]" class="required" autofocus /> <label for="email">Your Email* [[!+fi.error.email]]</label> <input type="email" name="email" id="email" value="[email protected][[!+fi.email]]" class="required" /> <label for="phone">Your Phone Number</label> <input type="tel" name="phone" id="phone" value="555-555-5555" /> <label for="budget">Project Budget</label> <input type="text" name="budget" id="budget" value="Ex. $5000 - $10k" /> </fieldset> <fieldset class="comment"> <label for="comments">Questions or Comments* [[!+fi.error.comments]]</label> <textarea id="comments" name="comments" class="required" cols="" rows="">[[!+fi.comments]]</textarea> <button type="submit" id="submitBtn">Send</button> </fieldset> </form>

В этом примере мы проверяем два поля ввода и область текста: Name, Email и Comments.

Элементы, которые подлежат проверке должны иметь класс class="required"

Добавим проверку полей с помощью jQuery.

Код
$(document).ready(function(){ $("form#contactForm").submit(function() { //When the form is submitted }); }); 

Мы должны споймать формы на отправке сообщения, чтобы убедиться в том, что подлежащие проверке поля имеют значения.

Код
$(document).ready(function(){ $("form#contactForm").submit(function() { //When the form is submitted var elem = $("form#contactForm").children('fieldset').children('input, textarea'); var error,foc; //Loop through each input and textarea elem.each(function(index){ //Does this have the class "required"? if($(this).hasClass('required')==true){ //It has the class, is it empty or still have the default value? if(!this.value || this.value == this.defaultValue ) { //Add the error class for CSS styling $(this).addClass("error"); //Switch the error var to true error = true; //If this is the first required element not filled out, save the ID if(!foc)foc = $(this).attr("id"); }else{ //If this is filled out make sure it doesn't have the error class $(this).removeClass("error"); } } }); //If error has been switched to true if (error){ //Focus on the first required element that hasn't been filled out. if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus(); //Stop the form from submitting return false; }else{ //Clear default values on non required elements before submit continues if(elem.value == this.defaultValue) this.value = ""; } }); }); 

Теперь у нас есть контроль над формой и мы можем добавить нашу проверку.

Отлично, давайте разберём этот код по частям.

Во-первых мы выбрали наши элементы используя переменную "elem":

Код
var elem = $("form#contactForm").children('fieldset').children('input, textarea');

Далее мы прошли через каждый элемент:

Код
elem.each(function(index){

Если он содержит класс "required", то проверялось пустое ли значение или значение по-умолчанию:

Код
if($(this).hasClass('required')==true){ if(!this.value || this.value == this.defaultValue ) {

Если он не соответствовал требованиям шла установка "error" в true и сохранение ID:

Код
//Добавьте класс ошибки в CSS $(this).addClass("error"); error = true; if(!foc)foc = $(this).attr("id"); //Если "foc" (focus) пуст назначить его ID первого элемента, который не соответствует требованию.

Если ошибка установлена в true, фокус переходил на первый требуемый элемент и возвращался false (прерывание отравки):

Код
if (error){ if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus(); return false;

Если все требуемые поля заполнены, очистка значений по-умолчанию непроверяемых полей и разрешение на отправку сообщения:

Код
else{ //Очистка значений по-умолчанию непроверяемых элементов перед отправкой сообщения if(elem.value == this.defaultValue) this.value = "";

Проверка Email поля

Мы убедились в том, что все требуемые поля заполнены, теперь нам нужно убедится, что пользователь заполнил поле почты правильно.

Код
function isEmail(emailAddress) { var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); return pattern.test(emailAddress); };

Регулярное выражение выше проверяет формат адреса и возвращает true, если он валидный.

Код
var email = $("input#email"); //Если поле почты email заполнено, то функция isEmail возвращает true if(email && !isEmail(email.val())) { email.focus(); email.prev("label").html("<span>Please Enter A Valid Email Address</span>"); error = true; }else{ email.prev("label").html("Your Email*"); } 

Если email не валидный, то метка будет заменена нашим сообщением о ошибке, если адрес в порядке, то сообщение останется неизменным.

Давайте сложим всё вместе

validate-form.js

Код
function isEmail(emailAddress) { var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); return pattern.test(emailAddress); }; $(document).ready(function(){ $("form#contactForm").submit(function() { //When the form is submitted var email = $("input#email"); var elem = $("form#contactForm").children('fieldset').children('input, textarea'); var error,foc; //If email is filled in and the function isEmail returns true if(email && !isEmail(email.val())){ email.focus(); email.prev("label").html("<span>Please Enter A Valid Email Address</span>"); error = true; }else{ email.prev("label").html("Your Email*"); } //Loop through each input and textarea elem.each(function(index){ //Does this have the class "required"? if($(this).hasClass('required')==true){ //It has the class, is it empty or still have the default value? if(!this.value || this.value == this.defaultValue ) { //Add the error class for CSS styling $(this).addClass("error"); //Switch the error var to true error = true; //If this is the first required element not filled out, save the ID if(!foc)foc = $(this).attr("id"); }else{ //If this is filled out make sure it doesn't have the error class $(this).removeClass("error"); } } }); //If error has been switched to true if (error){ //Focus on the first required element that hasn't been filled out. if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus(); //Stop the form from submitting return false; }else{ //Clear default values on non required elements before submit continues if(elem.value == this.defaultValue) this.value = ""; } }); //Remove Default Text On Focus $("input, textarea").focus(function() { if( this.value == this.defaultValue ) { this.value = ""; $(this).css("color","#000").css("fontStyle","normal"); } }).blur(function() { if( !this.value.length ) { $(this).css("color","#999").css("fontStyle","italic"); this.value = this.defaultValue; } }); }); 

Чанк: contactFormTpl:

Код
<p>Name: [[+name]]</p> <p>Email: [[+email]]</p> <p>Phone: [[+phone]]</p> <p>Budget: [[+budget]]</p> <p>Comments: [[+comments]]</p>

HTML код страницы контакта

Код
[[!FormIt? &hooks=`email,redirect` &emailTpl=`contactFormTpl` &emailFrom=`[email protected]` &emailFromName=`Your Site Name` &emailSubject=`Message From Your Site Name` &emailTo=`[email protected]` &redirectTo=`36` &validate=`name:required, email:email:required, comments:required:stripTags` ]] <form id="contactForm" action="[[~[[*id]]]]" method="post"> <fieldset> <label for="name">Your Name* [[!+fi.error.name]]</label> <input type="text" name="name" id="name" value="First and last name[[!+fi.name]]" class="required" autofocus=""> <label for="email">Your Email* [[!+fi.error.email]]</label> <input type="email" name="email" id="email" value="[email protected][[!+fi.email]]" class="required"> <label for="phone">Your Phone Number</label> <input type="tel" name="phone" id="phone" value="555-555-5555"> <label for="budget">Project Budget</label> <input type="text" name="budget" id="budget" value="Ex. $5000 - $10k"> </fieldset> <fieldset class="comment"> <label for="comments">Questions or Comments* [[!+fi.error.comments]]</label> <textarea id="comments" name="comments" class="required" cols="" rows="">[[!+fi.comments]]</textarea> <button type="submit" id="submitBtn">Send</button> </fieldset> </form>
2011