Создаем кастомную форму регистрации пользователей на WordPress. Создаем кастомную форму регистрации пользователей на WordPress Добавление новых полей в форму регистрации

Here is an example of html code for student registration form. In this example, we have displayed many text fields, radio button, Reset button and Submit Form button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in student registration form.

Here is an example of html code for student registration form. In this example, we have displayed many text fields, radio button, Reset button and Submit Form button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in student registration form. html code for student registration form

Here is an example of html code for student registration form. In this example, we have displayed many text fields, radio button, Reset button and Submit Form button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in student registration form. If you will not enter value in text field than an error message will be show. In this example we have made entry in every field mandatory hence an error is shown if one of them is not filled correctly. However, a programmer can make adjust it accordingly.

When all fields are filled correctly, submit form adds the data. A programmer can use this submit form as he/she wants, either they can send/redirect it to other page or save it in database.

Here is the video tutorial of "How to create student registration form in HTML?":

In the above video instruction we have explained you how to make html page for student registration and validate it with JavaScript. JavaScript is used to validate the HTML page in web applications. These days Ajax and jQuery is also used for making dynamic web applications.

StudentRegistration.html

Student Registration Form
Name
Father Name
Postal Address
Personal Address
Sex Male Female
City select.. NEW DELHI MUMBAI GOA PATNA
Course select.. B.TECH MCA MBA BCA
District select.. NALANDA UP GOA PATNA
State select.. NEW DELHI MUMBAI GOA BIHAR
PinCode
EmailId
DOB
MobileNo

Form Validation

Function validate() { if(document.StudentRegistration.textnames.value == "") { alert("Please provide your Name!"); document.StudentRegistration.textnames.focus() ; return false; } if(document.StudentRegistration.fathername.value == "") { alert("Please provide your Father Name!"); document.StudentRegistration.fathername.focus() ; return false; } if(document.StudentRegistration.paddress.value == "") { alert("Please provide your Postal Address!"); document.StudentRegistration.paddress.focus() ; return false; } if(document.StudentRegistration.personaladdress.value == "") { alert("Please provide your Personal Address!"); document.StudentRegistration.personaladdress.focus() ; return false; } if ((StudentRegistration.sex.checked == false) && (StudentRegistration.sex.checked == false)) { alert ("Please choose your Gender: Male or Female"); return false; } if(document.StudentRegistration.City.value == "-1") { alert("Please provide your City!"); document.StudentRegistration.City.focus() ; return false; } if(document.StudentRegistration.Course.value == "-1") { alert("Please provide your Course!"); return false; } if(document.StudentRegistration.District.value == "-1") { alert("Please provide your Select District!"); return false; } if(document.StudentRegistration.State.value == "-1") { alert("Please provide your Select State!"); return false; } if(document.StudentRegistration.pincode.value == "" || isNaN(document.StudentRegistration.pincode.value) || document.StudentRegistration.pincode.value.length != 6) { alert("Please provide a pincode in the format ######."); document.StudentRegistration.pincode.focus() ; return false; } var email = document.StudentRegistration.emailid.value; atpos = email.indexOf("@"); dotpos = email.lastIndexOf("."); if (email == "" || atpos

Из этого туториала Вы узнаете, как внести изменения в страницу регистрации в Joomla 3.x.

Изменение названий полей регистрационной формы

Для того чтобы изменить названия полей регистрационной формы, следуйте таким инструкциям:

Для того чтобы внести изменения в поля регистрационной формы, внесите изменения в файл en-GB.com_users.ini , расположенный в папке language/en-GB на вашем сервере. Используйте команду CTRL+F , для того чтобы найти текст, который Вы хотите изменить. Вы можете изменить следующие названия полей в файле en-GB.com_users.ini :

    Обязательные поля

    (Required field)

    Название

    Имя пользователя

  • Подтверждение пароля

    (Confirm Password)

    Адрес электронной почты

    Подтверждения адреса электронной почты

    (Confirm email Address)

    необязательно

Редактируйте файл en-GB.plg_user_profile.ini , расположенный в папке administrator/language/en-GB на вашем сервере, для того чтобы изменить нижеперечисленные заголовки:

    Адрес 1 (Address 1)

    Адрес 2 (Address2)

    Город (City)

    Регион (Region)

    Страна (Country)

    Почтовый индекс (Postal / ZIP Code)

    Телефон (Phone)

    Сайт (Web site)

    Любимая книга (Favourite Book)

    Про меня (About Me)

    Введённая дата рождения должна иметь формат Год-Месяц-День, например: 0000-00-00

    Дата рождения (Date of Birth)

Для того чтобы изменить названия кнопок «Зарегистрироваться» (Registration) и «Отменить» (Cancel), редактируйте файл en-GB.ini из папки language/en-GB вашего сервера.

Удаление полей из формы регистрации

Для того чтобы отключить какие-то из полей вашей регистрационной формы, Вам необходимо сделать следующее:


Добавление новых полей в форму регистрации

Для того чтобы добавить новые поля в форму регистрации, необходимо вносить изменения как в файлы шаблона, так и в базу данных. Вам необходимо внести следующие изменения в базу данных:


Для того чтобы новое поле отображалось на вашем сайте, внесите измнения в следующие файлы:

Внесите изменения в файл user.php из папки libraries/joomla/user . Найдите код поля, после которого должно быть добавлено новое поле:

Public $name = null;

Добавьте код для нового поля после этого кода:

Public $field_lable_here= null;

где field_name - это название вашего поля.

Также внесите изменения в файл users.xml из папки administrator/components/com_users/models/forms .

Найдите код поля, после которого будет выводится добавляемое поле:

Добавьте код для вашего поля после этого кода:

Замените field_lable_here вашим названием поля. Также измените Ваше описание на необходимое Вам описание.

Внесите изменения в файл registration.xml из папки components/com_users/models/forms вашего сервера. Добавьте код для вашего поля под код того поля, под которым новое поле должно выводиться.

В этой статье вы узнаете, как создать форму регистрации и авторизации , используя HTML, JavaScript, PHP и MySql. Такие формы используются почти на каждом сайте, в независимости от его типа. Они создаются и для форума, и для интернет-магазина и для социальных сетей (такие как например Facebook, Twiter, Odnoklassniki) и для многих других типов сайтов.

Если у Вас сайт на локальном компьютере, то я надеюсь, что у Вас уже . Без него ничего работать не будет.

Создание таблицы в Базе Данных

Для того чтобы реализовать регистрацию пользователей, в первую очередь нам нужна База Данных. Если она у Вас уже есть, то замечательно, иначе, Вам нужно её создавать. В статье , я подробно объясняю, как сделать это.

И так, у нас есть База Данных (сокращённо БД), теперь нам нужно создать таблицу users в которой будем добавлять наших зарегистрированных пользователей.

Как создавать таблицу в БД, я также объяснил в статье . Перед тем как создать таблицу, нам необходимо определить какие поля она будет содержать. Эти поля будут соответствовать полям из формы регистрации.

Значит, подумали, представили какие поля будут у нашей формы и создаём таблицу users с такими полями:

  • id - Идентификатор. Поле id должно быть у каждой таблицы из БД.
  • first_name - Для сохранений имени.
  • last_name - Для сохранений фамилии.
  • email - Для сохранений почтового адреса. E-mail мы будем использовать в качестве логина, поэтому это поле должна быть уникальной, то есть иметь индекс UNIQUE.
  • email_status - Поле для указания, подтверждена ли почта или нет. Если почта подтверждена, то оно будет иметь значение 1, иначе значение 0. По умолчанию, это поле будет иметь значение 0.
  • password - Для сохранений пароля.

Все поля типа “VARCHAR” должны иметь значение по умолчанию NULL.


Если Вы хотите чтобы Ваша форма регистрации имела ещё какие-то поля, то Вы можете их здесь также добавить.

Всё, наша таблица users готова. Переходим к следующему этапу.

Подключение к Базе Данных

Базу данных мы создали, теперь необходимо к ней подключиться. Подключение будем осуществлять с помощью PHP расширения MySQLi.

В папке нашего сайта, создаём файл с именем dbconnect.php , и в нём пишем следующий скрипт:

Этот файл dbconnect.php нужно будет подключить к обработчикам форм.

Обратите внимание на переменную $address_site , здесь я указал название моего тестового сайта, над которым буду работать. Вы соответственно, укажите название Вашего сайта.

Структура сайта

Теперь давайте разберёмся с HTML структурой нашего сайта.

Шапку и подвал сайта вынесем в отдельные файлы, header.php и footer.php . Их будем подключать на всех страницах. А именно на главной (файл index.php ), на страницу с формой регистрации (файл form_register.php ) и на страницу с формой авторизации (файл form_auth.php ).

Блок с нашими ссылками, регистрация и авторизация , добавим в шапку сайта, чтобы они отображались на всех страницах. Одна ссылка будет ввести на страницу с формой регистрации (файл form_register.php ) а другая на страницу с формой авторизации (файл form_auth.php ).

Содержимое файла header.php:

Название нашего сайта

В итоге, главная страница, у нас выглядит так:


Конечно, у Вас на сайте может быть совсем другая структура, но это для нас сейчас не важно. Главное, чтобы присутствовали ссылки (кнопки) регистрации и авторизации.

Теперь перейдём к форме регистрации. Как Вы уже поняли, она у нас находится в файле form_register.php .

Идём в Базу Данных (в phpMyAdmin), открываем структуру таблицы users и смотрим какие поля нам нужны. Значит, нам нужны поля для ввода имени и фамилии, поле для ввода почтового адреса(Email) и поле для ввода пароля. И ещё в целях безопасности добавим поле для ввода капчи.

На сервере, в результате обработки формы регистрации, могут возникнуть различные ошибки, из-за которых пользователь не сможет зарегистрироваться. Поэтому для того чтобы пользователь понимал почему не проходит регистрация, необходимо вывести ему сообщения об этих ошибках.

Перед выводом формы добавляем блок для вывода сообщений об ошибках из сессии.

И ещё момент, если пользователь уже авторизован, и он ради интереса заходит на страницу регистрации напрямую, написав в адресную строку браузера адрес_сайта/form_register.php , то мы в этом случае вместо формы регистрации, выведем ему заголовок о том, что он уже зарегистрирован.

В общем, код файла form_register.php у нас получился таким:

Вы уже зарегистрированы

В браузере, страница с формой регистрации выглядит так:


С помощью атрибута required , мы сделали все поля обязательными к заполнению.

Обратите внимание на код формы регистрации где выводится капча :


Мы в значение атрибута src для изображения, указали путь к файлу captcha.php , который генерирует данную капчу.

Посмотрим на код файла captcha.php :

Код хорошо закомментирован, поэтому я остановлюсь только на одном моменте.

Внутри функции imageTtfText() , указан путь к шрифту verdana.ttf . Так вот для корректной работы капчи, мы должны создать папку fonts , и поместить туда файл шрифта verdana.ttf . Его Вы можете найти и скачать из интернета, или взять из архива с материалами данной статьи .

С HTML структурой мы закончили, пора двигаться дальше.

Проверка email на валидность с помощью jQuery

Любая форма нуждается в проверки на валидность введённых данных, как на стороне клиента (с помощью JavaScript, jQuery), так и на стороне сервера.

Особенную внимательность мы должны уделить полю Email. Очень важно чтобы введённый почтовый адрес был валидным.

Для данного поля input, мы задали тип email (type="email"), это нас немножко предостерегает от неправильных форматов. Но, этого недостаточно, потому что через инспектор кода, которого предоставляет нам браузер, можно легко изменить значение атрибута type с email на text , и всё, наша проверка будет уже недействительна.


И в таком случае, мы должны сделать более надёжную проверку. Для этого, воспользуемся библиотекой jQuery от JavaScript.

Для подключения библиотеки jQuery, в файле header.php между тегами , перед закрывающего тега , добавляем эту строчку:

Сразу после этой строчки, добавим код проверки валидации email. Здесь же добавим код проверки длины введённого пароля. Его длина должна быть не меньше 6 символов.

С помощью данного скрипта, мы проверяем введённого почтового адреса на валидность. Если пользователь ввёл неправильный Email, то мы выводим ему ошибку об этом и дезактивируем кнопку отправки формы. Если всё хорошо, то мы убираем ошибку и активируем кнопку отправки формы.

И так, с проверкой формы на клиентской части мы закончили. Теперь мы можем отправить её на сервер, где также сделаем пару проверок и добавим данные в БД.

Регистрация пользователя

Форму мы отправляем на обработку файлу register.php , через метод POST. Название данного файла обработчика, указано в значение атрибута action . А метод отправки указано в значение атрибута method .

Открываем этот файл register.php и первое что нам нужно сделать, это написать функцию запуска сессии и подключить созданный нами ранее файл dbconnect.php (В этом файле мы сделали подключение к БД). И ещё, сразу объявим ячейки error_messages и success_messages в глобальном массиве сессии. В error_mesages будем записывать все сообщения об ошибках возникающие при обработке формы, а в succes_messages , будем записывать радостные сообщения.

Перед тем как продолжить, мы должны проверить, была ли вообще отправлена форма . Злоумышленник, может посмотреть на значение атрибута action из формы, и узнать какой файл занимается обработкой данной формы. И ему может прийти в голову мысль перейти напрямую в этот файл, набирая в адресной строке браузера такой адрес: http://арес_сайта/register.php

Поэтому нам нужно проверить наличие ячейки в глобальном массиве POST, имя которой соответствует имени нашей кнопки "Зарегистрироваться" из формы. Таким образом мы проверяем была ли нажата кнопка "Зарегистрироваться" или нет.

Если злоумышленник попытается перейти напрямую в этот файл, то он получить сообщение об ошибке. Напоминаю, что переменная $address_site содержит название сайта и оно было объявлено в файле dbconnect.php .

Значение капчи в сессии было добавлено при её генерации, в файле captcha.php . Для напоминания покажу ещё раз этот кусок кода из файла captcha.php , где добавляется значение капчи в сессию:

Теперь приступим к самой проверке. В файле register.php , внутри блока if, где проверяем была ли нажата кнопка "Зарегистрироваться", а точнее где указан комментарий " // (1) Место для следующего куска кода " пишем:

//Проверяем полученную капчу //Обрезаем пробелы с начала и с конца строки $captcha = trim($_POST["captcha"]); if(isset($_POST["captcha"]) && !empty($captcha)){ //Сравниваем полученное значение с значением из сессии. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){ // Если капча не верна, то возвращаем пользователя на страницу регистрации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу. $error_message = "

Ошибка! Вы ввели неправильную капчу

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (2) Место для следующего куска кода }else{ //Если капча не передана либо оно является пустой exit("

Ошибка! Отсутствует проверечный код, то есть код капчи. Вы можете перейти на главную страницу .

"); }

Далее, нам нужно обрабатывать полученные данные, из массива POST. Первым делом, нам нужно проверить содержимое глобального массива POST, то есть находится ли там ячейки, имена которых соответствуют именам полей input из нашей формы.

Если ячейка существует, то обрезаем пробелы с начала и с конца строки из этой ячейки, иначе, перенаправляем пользователя обратно на страницу с формой регистрации.

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

Этот код вставляем в указанное место "// (2) Место для следующего куска кода ".

/* Проверяем если в глобальном массиве $_POST существуют данные отправленные из формы и заключаем переданные данные в обычные переменные.*/ if(isset($_POST["first_name"])){ //Обрезаем пробелы с начала и с конца строки $first_name = trim($_POST["first_name"]); //Проверяем переменную на пустоту if(!empty($first_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $first_name = htmlspecialchars($first_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваше имя

Отсутствует поле с именем

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["last_name"])){ //Обрезаем пробелы с начала и с конца строки $last_name = trim($_POST["last_name"]); if(!empty($last_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $last_name = htmlspecialchars($last_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Вашу фамилию

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле с фамилией

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["email"])){ //Обрезаем пробелы с начала и с конца строки $email = trim($_POST["email"]); if(!empty($email)){ $email = htmlspecialchars($email, ENT_QUOTES); // (3) Место кода для проверки формата почтового адреса и его уникальности }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["password"])){ //Обрезаем пробелы с начала и с конца строки $password = trim($_POST["password"]); if(!empty($password)){ $password = htmlspecialchars($password, ENT_QUOTES); //Шифруем папроль $password = md5($password."top_secret"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш пароль

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (4) Место для кода добавления пользователя в БД

Особенную важность имеет поле email . Мы должны проверить формат полученного почтового адреса и его уникальность в БД. То есть не зарегистрирован ли уже какой-то пользователь с таким же почтовым адресом.

В указанном месте "// (3) Место кода для проверки формата почтового адреса и его уникальности " добавляем следующий код:

//Проверяем формат полученного почтового адреса с помощью регулярного выражения $reg_email = "/^**@(+(*+)*\.)++/i"; //Если формат полученного почтового адреса не соответствует регулярному выражению if(!preg_match($reg_email, $email)){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Вы ввели неправельный email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } //Проверяем нет ли уже такого адреса в БД. $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`="".$email."""); //Если кол-во полученных строк ровно единице, значит пользователь с таким почтовым адресом уже зарегистрирован if($result_query->num_rows == 1){ //Если полученный результат не равен false if(($row = $result_query->fetch_assoc()) != false){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Пользователь с таким почтовым адресом уже зарегистрирован

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка в запросе к БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); } /* закрытие выборки */ $result_query->close(); //Останавливаем скрипт exit(); } /* закрытие выборки */ $result_query->close();

И так, мы закончили со всеми проверками, пора добавить пользователя в БД. В указанном месте " // (4) Место для кода добавления пользователя в БД " добавляем следующий код:

//Запрос на добавления пользователя в БД $result_query_insert = $mysqli->query("INSERT INTO `users` (first_name, last_name, email, password) VALUES ("".$first_name."", "".$last_name."", "".$email."", "".$password."")"); if(!$result_query_insert){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка запроса на добавления пользователя в БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); }else{ $_SESSION["success_messages"] = "

Регистрация прошла успешно!!!
Теперь Вы можете авторизоваться используя Ваш логин и пароль.

"; //Отправляем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); } /* Завершение запроса */ $result_query_insert->close(); //Закрываем подключение к БД $mysqli->close();

Если в запросе на добавления пользователя в БД произошла ошибка, мы добавляем сообщение об этой ошибке в сессию и возвращаем пользователя на страницу регистрации.

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

Скрипт для проверки формата почтового адреса и длины пароля находится в файле header.php , поэтому он будет действовать и на поля из этой формы.

Запуск сессии также происходит в файле header.php , поэтому в файле form_auth.php сессию запускать не нужно, потому что получим ошибку.


Как я уже сказал, скрипт проверки формата почтового адреса и длины пароля здесь также действует. Поэтому если пользователь введёт неправильный почтовый адрес или короткий пароль, то он сразу же получить сообщение об ошибке. А кнопка войти станет не активной.

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

Авторизация пользователя

В значение атрибута action у форы авторизации указан файл auth.php , это значит, что форма будет обрабатываться именно в этом файле.

И так, открываем файл auth.php и пишем код для обработки формы авторизации. Первое что нужно сделать это запустить сессию и подключить файл dbconnect.php для соединения с БД.

При нажатии на ссылку выхода с сайта, мы попадаем в файл logout.php , где просто уничтожаем ячейки с почтовым адресом и паролем из сессии. После этого возвращаем пользователя обратно на ту страницу, на которой была нажата ссылка выход .

Код файла logout.php:

На этом всё. Теперь Вы знаете как реализовать и обрабатывать формы регистрации и авторизации пользователя на своём сайте. Эти формы встречаются почти на каждом сайте, поэтому каждый программист должен знать, как их создавать.

Ещё мы научились проверять вводимые данные, как на стороне клиента (в браузере, с помощью JavaScript, jQuery) так и на стороне сервера (с помощью языка PHP). Также мы научились реализовать процедуру выхода с сайта .

Все скрипты проверены и рабочие. Архив с файлами этого маленького сайта Вы можете скачать по этой ссылке .

В будущем я напишу статью где опишу . И ещё планирую написать статью где объясню, (без перезагрузки страницы). Так что, для того чтобы быть в курсе о выходе новых статей можете подписаться на мой сайт.

При возникновении вопросов обращайтесь, также, если вы заметили, какую-то ошибку в статье прошу вас, сообщите, мне об этом.

План урока (Часть 5):

  • Создаем HTML структуру для формы авторизации
  • Обрабатываем полученные данные
  • Выводим приветствие пользователя в шапку сайта
  • Понравилась статья?

    Disclosure: Your support helps keep the site running! We earn a referral fee for some of the services we recommend on this page. Learn more

    Sharing is caring!

    Last Updated on December 17, 2019

    Web forms are used by virtually all websites for a wide range of purposes. Users of forums and social networks use forms to add content and interact with other users. Websites that can be customized to create a personalized experience, such as customizable newsfeeds, use forms to allow users to control the content that appears on the page. And nearly every website uses forms to allow website visitors to contact the organization or person administering the website. Web forms are made possible by the integration of multiple technologies:

    • HTML to create the form fields and labels and accept user input.
    • CSS to style the presentation of the form.
    • JavaScript to validate form input and provide Ajax -enabled interactions.
    • Server-side languages such as PHP to process form data.

    In this guide, we"re going to cover all of the HTML elements used to create web forms. We also have other that cover topics such as building a form , styling and designing forms , and ensuring form usability and accessibility .

    Defining the Structure of a Form

    Paragraph content.

    Contact Form

    Name:

    Email:

    Subject:

    Message: Type your message here

    Additional paragraph content

    When rendered in the browser, the contact form would be clearly separated from surrounding content.

    The fieldset element is optional but is commonly used to group related elements on long and complex forms, or to isolate form fields from nearby elements when a form is presented along with non-form content. HTML5 added three attributes which can be applied to fieldset elements:

    • disabled: Used to disable all of the forms in a fieldset. Note that we used this attribute in the example form above.
    • form: Used to associate a fieldset with the id of one or more form elements. Note that browser support for this attribute is very limited.
    • name: Associates a name with the fieldset .
    The Input Element

    Depending on the type of form you are creating, it"s entirely possible to have a form that only includes two types of elements: one form element and one or more input elements. The element is used to create a variety of different types of input fields for form users to interact with.

    Common Values

    The input element is a very flexible element who appearance and behavior can change dramatically based on the type attribute applied to the element. The most common type values include: text : The default value for the type="" attribute. Defines a single line of text 20 characters wide. The width can be adjusted with the size attribute as you can see in the form code in our previous example. password : The password type is basically the same as the text field with the exception that characters entered into a password field are masked. radio : Radio buttons can be used to provide multiple options of which only one may be chosen. checkbox : Checkboxes are similar to radio buttons, but more than one selection can be active at a time. This means multiple values can be submitted with a set of checkboxes while a set of radio buttons will only accept one value. submit : The submit type value creates a form submission button. When clicked, the form will take the action specified in the action attribute associated with the form element. Many forms make use of just one or two input types, and most simple forms are built using just the types listed above. However, there are many additional types you can use to accept form data that doesn"t fit into any of the types listed above.

    Less Common Values

    These input types are less common than those listed above but are supported by virtually all browsers and can be used to build many different types of form inputs. button : If you want to run a when a button is clicked, the button input type can be used to create a button which can be associated with a variety of actions. hidden : This attribute type is usually used simultaneously with the value attribute, which we"ll cover momentarily, to add a pre-defined value to every form submission. For example, if you have contact forms on five different pages you could add to each form to submit the name of the page where the contact form was submitted from. reset : This type is used to create a reset button that will return all form fields to their default state. file : If you want to allow form users to upload and submit files, will provide that capability. image : In the past, it was common to use an image as a submit button. While this type value is still valid, it is not used very frequently in modern web form design. Instead, use CSS to style the button.

    New Values Added by HTML5

    Several additional input types are defined by the HTML5 specification. Many of these types have limited browser support. So if you use them, be sure to check caniuse.com for browser support and provide adequate fallback options where appropriate. search : This is the proper type to specify if your form provides search functionality. Unlike most of the other types of inputs added in HTML5, type="search" is supported by all browsers. Just remember that this feature doesn"t actually provide search functionality, it just creates a form input field designed to be used as a part of a search feature. color : When this input type is specified it will display a colored-button that launches a basic color selector tool. Set the default color value by using the value attribute and a hex color code like this: . number : This type produces a field for entering a number which has increment buttons on the righthand side of box. Limits can be placed on the range of acceptable entries with the max , min , and step attributes, but browsers that lack support for this element typically fallback to a standard text input that does not recognize these limits. range : Browser support for this element is pretty good with a few exceptions. Use this attribute to produce a slider which can be used to select a value within a specified range. For example, this code would produce a slider to select a number between 100 and 1000 in increments of 50: . You"ll need to pair the range element with another technique to provide a live preview of the selected value. Thankfully, HTML5 Doctor has a simple way to do this using the output element. Date and Time Types : HTML5 added a number of input types that can be used to specify time and date values. For example, the date type defines a control to enter a year, month, and day. To add time to the date input, use datetime-local . If you want time without date information use the time input type. Less specific input types include the month and week options which can be used to select a week or month within a year without specifying the day or time. Browsers have been slow to add support for this type, so be sure to check for browser support and provide fallbacks if you use this type of input. Contact Detail Types : Broad support is available for the three input types used to collect pertinent details like email addresses (email), telephone numbers (tel), and website URLs (url).

    Common Input Attributes

    While the type attribute is by far the most-used and most useful input attribute, there are several other attributes you will need to know to build useful forms. name : The name assigned to an input element will be submitted along with the value entered into the associated field. In other words, if the value “Fred” were entered into an input element with this code the value submitted would be “first_name=Fred”. value : The value of an input element performs a different function depending on the type of input it is applied to. When applied to the submit , reset , or button types the value is used as the text on the button. When applied to text fields it provides the default value associated with the field. When associated with a checkbox or radio button, the value provides the value that will be associated with that field if selected.

    Who referred you to our website?:

    Pink:

    Red:

    readonly : When readonly is applied as an attribute of an input element the value in the field cannot be changed. JavaScript can be used to remove the readonly attribute after some other action is taken, such as clicking a button or selecting a checkbox. For example, readonly could be applied to a submit input type and removed when a checkbox was selected confirming that the user accepted the website"s terms of service. disabled : We used this attribute with example form embedded earlier in this tutorial. Use this attribute to disable an entire form, fieldset, a single field. size : Use the size attribute with text input types to specify the visible width of the field without limiting the number of characters that may be entered into the field. maxlength : If you don"t want to accept more than a certain number of characters in a given field, use maxlength to limit those fields to a defined number of characters. checked : If you want a checkbox or radio button to be preselected when a form loads apply this attribute to that input element. These attributes have broad support and are used commonly with forms you encounter every day.

    New Attributes Added by HTML5

    HTML5 added many new attributes which can be associated with input elements. Browser support for some of these elements is limited, so be sure to check for support and provide fallback options for users of unsupported browsers. autocomplete : If your form includes common fields, leaving autocomplete on will allow the visitors browser to suggest entries based on previously completed forms. autofocus : Use this attribute to identify the form field that should be in focus when the form loads. multiple : The multiple attribute can be used with email and file input types to allow form users to input more than one value. When used for email inputs, more than one email address can be submitted by separating each address from the next with a comma. When used for file inputs, multiple files may be selected and submitted simultaneously. pattern : There may be times when you want to specify that the value of an input must meet certain criteria. For example, you may want to require that a password field includes at least one uppercase letter, one lowercase letter, one number, and meets a minimum length requirement. The pattern attribute can be used to create expressions against which input values are validated. Writing these expressions, referred to as Regular Expressions or RegExp, is beyond the scope of this tutorial. You can learn about regular expressions at Wikipedia and then write and test your expressions for free at RegExr . placeholder : Most forms include placeholder text which disappears as soon as you click into the field or begin typing. Use this attribute to add and define placeholder text for any inputs that accept text. required : If certain fields in a form are required, use this attribute to prevent submission of incomplete forms. form : If you ever need to place an input element outside of the form element, you can associate the displaced element by using the form attribute and applying a value that matches the id attribute applied to the form. Modify Form Submit Button Behavior There are five attributes that can be applied to submit and image input types to override the attributes applied to the parent form element. These attributes include:

    • formaction : Define a different URL from the one identified in the parent form"s action attribute to process a form submission. Often used when forms may be processed in more than one way to provide a variety of form submission options.
    • formenctype : Specify an encoding type that should be used for form submissions. The value used overrides the value applied to the enctype attribute of the parent form element.
    • formmethod : This attribute is used specify either the get or post method value and will override the method attribute applied to the parent form .
    • formnovalidate : If you don"t want form input to be validated when submitted you can use this attribute.
    • formtarget : Override the target attribute applied to the parent form element by applying this attribute to a submit or image input type field.

    Define the Size of type="image" : If you use the image input type to create a form submission button, you can control the size of the image using the height and width attributes. Alternatively, you can do the same thing with CSS. Most developers and designers would recommend avoiding these attributes and controlling button appearance with CSS . Set Limits and Increments for Numeric Values : You can use the min , max , and step attributes to define minimum and maximum values as well as acceptable increments falling between these values for any input that accepts numeric values.

    Drop-Downs, Text Areas, & Buttons

    Inputs aren"t the only elements that can be used to create form fields. Other types of elements can be associated with forms to create drop-down lists or options, free-form text areas, and flexible buttons.

    Pre-Populated Drop-Down Lists

    To create a drop-down list of pre-populated options from which a website visitor can select an option, use the select element to create the field, and nest multiple option elements to create the various options that should appear in the drop-down menu. For example, to create a drop-down menu of pretentious color options for a fictional e-commerce store, the following code could be used:

    Windswept Sand Dune Lush Forest Turbulent Waters Deep Night

    Note that the value is what will actually be submitted with the form while the text between the opening and closing tags is what is presented to the visitor completing the form. For example, if a visitor selects “Lush Forest” the actual value submitted with the form will be green . Here"s how our drop-down list shows up in the browser:

    Windswept Sand Dune Lush Forest Turbulent Waters Deep Night

    Free Form Text Areas

    All of the text inputs we"ve seen so far, such as , only accept a single line of text. However, if you want to create a larger text area for longer text input a single line input field isn"t going to work. The textarea element is the correct choice for creating a large text input area capable of accepting text input that won"t render well on a single line. There are three parts to a textarea:

  • The textarea is created by inserting opening and closing tags. Any text nested between the tags will be loaded in the text area when the form loads and will be submitted along with the form unless the visitor submitting the form deletes the text out of the textarea .
  • If you want to define the size of the text area use the rows attribute to define the number of rows of text that should able to be displayed without resizing the text area.
  • To set a predefined width use the cols attribute. The value applied will be the number of characters that will appear on a single row before wrapping to the second row.
  • Text area elements are resizable. However, the rows and cols attributes will define the size of the textarea when it is first rendered by the browser and will also set the minimum space the area may be resized to fit.


    Enter Text Here

    This code will produce two identically sized text areas that are three rows tall and can accept 60 characters per row. They will be resizable to any size larger than the default size. Note how the placeholder text was added to the first with the placeholder element but simply nested between the opening and closing tags in the second example. Below you can see how these two bits of code are rendered.

    While textarea size can be specified using ‘rows" and ‘cols", it is a better practice to use CSS to style and size text areas. Many of the attributes that can be applied to input elements can also be applied to textarea elements. In addition, to those included in our example above, attributes that can be applied to text areas include: autofocus , disabled , form , maxlength , name , readonly , required , and wrap .

    Flexible Buttons

    There are two ways to create buttons for forms:

    We"ve already talked about the input element and the different types that can be used to create buttons. So why is there another button? There are least two ways that button elements are different from their input cousins.

  • Because buttons are made with an opening and closing tag, different types of content – usually text and images – can be nested between the opening and closing tags and will be rendered on the button.
  • Buttons do not have to be associated with a form element. They can be used as standalone buttons to initiate scripts, as the content of an anchor element, and to perform other actions.
  • Form Elements Added in HTML5

    Three new form elements were added in HTML5: datalist : Use this element to provide a list of suggested autocompletion values for an input element. In order to use the datalist element, first create an input element with a list attribute. Then create a datalist element with an id attribute. The value applied to the input list attribute must match the datalist id. Values are added to the datalist by adding option elements between the opening and closing datalist tags. Here"s an example of how this all works:

    When we render that code in the browser and input element will appear. If we begin typing, autocomplete suggestions will be made based on the options included in the datalist. Note that users submitting the form aren"t limited to selecting from one of these options. They can still choose to type a value that is not an included option if they wish to do so.

    What is your favorite web technology?

    output : Use this element to display the result of a calculation or user input. Associate it with an input element by using the for attribute with a value that matches the id of the relevant input element, or associate it with a form by adding a form attribute using a value that matches the id of the relevant form . The output element can also be paired with the range element to let form users know the exact value represented by the current position of the slider of a range element. Using the output and range elements in this way is beyond the scope of this introductory tutorial, but if you want to use these two elements together you can learn more about this technique at the HTML5 Doctor .

    Next Steps

    This tutorial has provided an overview of the elements used to build forms for the web. The next step is to try out some of the knowledge you"ve gained. Other tutorials in this section will walk you through the process of creating a reservation form , styling and designing forms , and ensuring that your forms meet usability and accessibility guidelines .

    Frequently Asked Questions How do you restrict a form field to only accept numbers?

    In the past, restricting a field to numbers only required the use of JavaScript. However, with the release of HTML5, it"s now simple to limit a field to numeric input only. Just apply the number value to the type attribute of the applicable input element. For example:

    When rendered, produces a text input field that will only accept numbers.

    How do you restrict a form field to only accept alphanumeric characters?

    In the past, the only way to limit field input to alphanumeric characters was to use jQuery or JavaScript and craft a custom function. However, HTML5 added the pattern attribute for input elements which can be used to restrict a form field to accept alphanumeric input only. Here"s the code that will do the trick:

    In this case, the pattern element will accept lowercase letters, uppercase letters, and numbers. The second part of the value in curly braces stipulates how many total characters may be entered into the field. Let"s see how that looks in the browser.

    The way it works is that when you attempt to submit values that don"t meet the specified pattern the title attribute is displayed. So you should put some instructions inside the pattern attribute so that users can figure out what they"ve done wrong. Browser support for this relatively new attribute is really pretty good. IE 9 and earlier versions of IE don"t support it and Opera Mini also lacks support. However, all other browsers do support the attribute.

    How do you make a form submit when the user presses enter?

    If you"ve come across a form that does not submit when you press enter, then someone has intentionally designed the form to behave that way – and they really shouldn"t have done that. Web accessibility specs are clear: design forms to allow implicit submission. What is implicit submission? Submitting a form by pressing enter. Browsers are designed to support implicit submission. Here"s how it works. Take this form for instance:

    Name:
    Age:

    If you were focused on any element in that form and pressed enter, the form would be submitted. This is implicit submission and all modern browsers support this behavior. Use the button element in the form and you don"t even have to use the submit value for the type attribute. Hit enter while focused on any element in this form and the form will still be submitted.

    Name:
    Age:
    Submit

    So how do developers break this behavior? One way to get around this behavior–and to be clear, we don"t recommend this–is to drop the form elements. The browser knows what to submit by grouping together everything between the form tags. Drop those tags and the browser doesn"t know what to submit. Another way some developers manipulate browser behavior is to use CSS to make buttons rather than proper HTML elements, like this.

    .submitButton { padding: 10px 20px; margin-top: 10px; background-color: #ddd; border-radius: 5px; display: inline-block; } .submitButton:hover { background-color: #ccc; } .submitButton:active { background-color: #ddd; } Name:
    Age:
    Submit

    Which, when rendered by the browser, would produce a button that looked like a button but did not do anything when enter is pressed.

    SubmitButton{padding: 10px 20px; margin-top: 10px; background-color: #ddd; border-radius: 5px; display: inline-block;}.submitButton:hover{background-color: #ccc;}.submitButton:active{background-color: #ddd;}

    На WordPress существует регистрационная форма, с помощью которой новые пользователи регистрируются на сайте. Но что делать, если вы хотите создать пользовательскую регистрационную форму, которая не отвечает параметрам Консоли в WordPress, и добавить в нее новые поля?

    | Скачать готовый плагин формы |

    Из сегодняшнего руководства вы узнаете, как создать регистрационную форму на WordPress с помощью комбинации тегов шаблонов и шорткодов.

    Стандартная регистрационная форма состоит только из двух полей – имени пользователя и e-mail.

    Наличие только двух полей в регистрационной форме для заполнения делает процесс регистрации очень простым. Сначала вы вводите имя пользователя и почтовый адрес, после чего пароль для входа на сайт автоматически приходит к вам на e-mail. Затем вы входите на сайт, используя присланный вам пароль, заполняете свой профиль и меняете пароль на новый, какой сами придумаете и легко сможете запомнить.

    А можно немного изменить вышеупомянутый процесс регистрации на вашем сайте и использовать дополнительные поля вместе с двумя уже имеющимися. Это может быть поле для пароля, URL-адрес сайта пользователя, любая личная информация, никнейм, фамилия и имя.

    И сегодня мы будем создавать WordPress-плагин для кастомной регистрационной формы с использованием следующих полей:

    • имя пользователя
    • пароль
    • e-mail
    • URL-адрес сайта
    • фамилия
    • никнейм
    • личная информация

    Пользовательская регистрационная форма может быть интегрирована на WordPress с помощью шорткода плагина и соответствующего тега шаблона.

    Шорткод позволяет создать страницу и сделать ее главной регистрационной страницей вашего сайта. Также можно использовать шорткод в посте, чтоб пользователь смог подписаться на обновления вашего сайта после прочтения одной из понравившихся статей.

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

    Перед тем как мы приступим к созданию плагина, стоит отметить, что нам нужны поля с именем пользователя, паролем и e-mail.

    Мы будем соблюдать это правило при создании функции проверки.

    Создание плагина

    Учитывая все вышесказанное, давайте приступим к написанию кода плагина. Сначала включите заголовок и шапку плагина.

    Заключение

    В сегодняшнем посте мы рассмотрели процесс создания плагина, с помощью которого добавляется кастомная регистрационная форма на сайте WordPress. На основе предоставленной информации можно расширить количество полей для заполнения, но только убедившись, что поля формы являются действительными мета-данными для wp_insert_user .