Форма входа и регистрации с помощью HTML5 и CSS3. Создание формы в HTML Безобидный login form register html

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

Первое поле – для логина, второе – для пароля. И вот со вторым не все так просто. Поскольку на текущий момент оно представляет собой просто поле для ввода текста.

Логин
Пароль

Результат в браузере:

Чтобы введенный в нем текст заменялся на звездочки, как это принято для поля такого типа, необходимо сделать одно простое действие. А именно, осуществить замену значения атрибута type на password :

Результат:

Кнопка отправки формы

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

Если на кнопке должна присутствовать какая-то надпись, то ее можно сделать, используя атрибут value . Задавать имя кнопке или нет – на ваше усмотрение, но если вы это сделаете, то сервер будет получать это имя, а также значение кнопки.

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

В итоге код нашей формы получится следующим:

Логин
Пароль

Результат в браузере:

Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.

Пример 1. Отправка данных формы

HTML5 IE Cr Op Sa Fx

Данные формы

В этом примере данные формы, обозначенные атрибутом name (login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.

Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.

Какой метод используется легко определить по адресной строке браузера. Если в ней появился вопросительный знак и адрес стал похож на этот, то это точно GET.

http://www.google.ru/search?q=%D1%81%D0%B8%D1%81%D1%8C%D0%BA%D0%B8&ie=utf-8

Уникальное сочетание параметров в адресной строке однозначно идентифицирует страницу, так что страницы с адресами?q=node/add и?q=node считаются разными. Эту особенность используют системы управления контентом (CMS, Content management system) для создания множества страниц сайта. В реальности же используется один файл, который получает запрос GET и согласно ему формирует содержимое документа.

Ниже перечислены типовые области применения этих методов на сайтах.

GET

Передача небольших текстовых данных на сервер; поиск по сайту.

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

POST

Пересылка файлов (фотографий, архивов, программ и др.); отправка комментариев; добавление и редактирование сообщений на форуме, блоге.

Работа с формой по умолчанию происходит в текущей вкладке браузера, при этом допустимо при отправке формы изменить этот параметр и открывать обработчик формы в новой вкладке или во фрейме. Такое поведение задаётся через «имя контекста», которое выступает значением атрибута target тега . Популярные значения это _blank для открытия формы в новом окне или вкладке, и имя фрейма, которое задаётся атрибутом name тега (пример 2).

Пример 2. Открытие формы во фрейме

HTML5 IE Cr Op Sa Fx

Использование фрейма

В данном примере при нажатии на кнопку «Отправить» результат отправки формы открывается во фрейме с именем area .

Элементы формы традиционно располагаются внутри тега , тем самым определяя те данные, которые будут передаваться на сервер. В то же время в HTML5 есть возможность отделить форму от её элементов. Это сделано для удобства и универсальности, так, сложный макет может содержать несколько форм, которые не должны пересекаться меж собой или к примеру, некоторые элементы выводятся с помощью скриптов в одном месте страницы, а сама форма находится в другом. Связь между формой и её элементами происходит в таком случае через идентификатор формы, а к элементам следует добавить атрибут form со значением, равным этому идентификатору (пример 3).

Пример 3. Связывание формы с полями

HTML5 IE Cr Op Sa Fx

Форма

В этом примере тег однозначно отождествляется через идентификатор auth , а к полям, которые следует отправить с помощью формы, добавляется form="auth" . При этом поведение элементов не меняется, при нажатии на кнопку логин и пароль пересылаются на обработчик handler.php.

Хотя параметры передачи формы традиционно указываются в теге , их можно перенести и в кнопки отправки формы ( и ). Для этого применяется набор атрибутов formaction , formmethod , formenctype и formtarget , которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.

Пример 4. Отправка формы

HTML5 IE Cr Op Sa Fx

Отправка формы

Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.

Login forms can be found in websites with forums, shops, WordPress and mostly everything on the internet requires login form somewhere to get access to something. The whole web is incomplete without login forms and registration, signups forms.

HTML forms will be first which most of us come across and with proper CSS which gives style to the HTML structure . In latest HTML versions i guess HTML seems to have opted for CSS3 as their default structure styling option. Anyways what you find here is the pre designed HTML, CSS forms built by front end developers and shared to the public for free to use.

Try to use all these free login form templates as most of them also have pre built HTML validation features as well as some opt jQuery or HTML validation (like the Login/Register form with pass meter below).

This list is not over yet, i am interested in finding new login form designs so i will keep updating these list with new login form templates when they show up in 2017. Stay tuned.

Red Login Form

A simple and effective login form for your website which requires basic input fields and no extra programming.

A flat login form design designed for your website which is already flat. Download and use this template for any purpose.

Require a quick signin for your clients ? No worries, this pretty looking login form will get you going without any hassles. Download the source code and check the demo as you can put a sample username and password in the fields and try to login. You will be taken to a profile page on the same which looks glorious with a logout button which shows the logging out animation.

With google material design getting popular over flat design we can see a deep and carefully shadowed login form and a register form in this css3 template.

Here you get another brilliant login form for your busienss website with a option to hide/show login fields. Well coded css/html/js design will give you better loading without tampering your current site speed.

Minimal Login Form with fluid animation

A smooth animation of login form which opens up the login section by clicking a picture or a button as you need.

Minimalistic Login Form with css

Here you will find a no-fancy login form ui which is placed on a full screen background. The download file will get you css and html for easy implementation of this login to your website.

Animated Login Form

The click animations displayed on text fields is brilliant which displays a small sliding animation of user and password icons. You can then login the form to watch a authenticating pre loader as well as a welcome back block. This download contains all the source files to implement a login form for your own website.

Elegant Login

This is a simple version of login form you can display on your website as this also has less impact on site speed with its minimal code.

Calm Login Screen

A clean login form with animated background giving a relaxing feel to the whole page. Download the whole template in zip format from codepen.

Login and Signup Form

Integrate this fluid login and signup form on to your website with ease. The zip file with this download will provide you with css, html and js templates. Social media signup is also available with password show/hide options for on screen easy password entry.

Login Form with Create Account

A login form which displays with a fadein effect is just amusing to watch. This effect can be seen only in few modern login forms. Use the click me to change the form to signup or create form.

A minimal style login form with flat design can be download from the link below. HTML validation is available and set in this login template.

Download Minimal Form Template for Login

A validation for email is in palce and this tempalte is pure css, html with no fancy jquery modules.

Download Signup/Login Form

A single form to login to the website as well as a signup, register option which can be flipped with a click. Even though the signup area is missing some important fields this is nonetheless better form with all powerful features.

Download

This login form is hidden unles you click on login link. This is a very useful feature for modern day website which can avoid an extra page for login. Display login on any page you like with this powerful login form.

Download

It’s provided both as a PSD and as a fully-coded HTML/CSS version, so you can get started integrating it straight away.

Login Form (Coded)

A professional login form. The download includes the PSD file, and I also felt like coding it so I included the xHTML, Js and CSS files as well.

Download

White Simple Login Form

A clean and simple login form with a round submit button and elegant focus states.

Simply Login Form

Simply Login Form styled and designed purely using CSS3. The form is created using pretty simple markup and styled using very basic CSS3 properties.

Download

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in Login page. We have set username and password value. If a person enter a wrong username or password or both, an error message with "Error: Incorrect Username or Password" will be displayed. Till the person enters the correct username and password, it will not Login.

Once you enter the correct Username and Password, you will be redirected to another page.

Login page is used in most of the dynamic website to validate user based on their credentials. For making login page for websites HTML form and HTML elements are used. Text field is used to accept username and password text field is used to accept password from user.

The submit button is used for submitting data to server for validation. Its good to validate user input in the browser using JavaScript. In this tutorial we are creating a HTML Login page code and validating user input with JavaScript. In modern web application server-side validation is also very important it is done on server side with the program running on the server.

Here is video tutorial:

But in this tutorial you will learn to create a login page in HTML and validate user input with JavaScript. View demo of HTML Login page .

Here is the screen shot of the the login page we are making:

This login page displays Username, Password text fields and then buttons for reset and Login. Once user enters the data and clicks on the Login button, JavaScript is used to validate the form and error message is displayed if validation fails.

HTML Login page with JavaScript Validation

Login Page

HTML Login Page
Username:
Password:
function check(form) { if(form.userid.value == "Roseindia" && form.pwd.value == "Roseindia") { return true; } else { alert("Error Password or Username") return false; } }

The tag of HTML is the heart of creating user entry form in web application which takes the user input data and finally submit it to server side program for further processing. Data of all the input or hidden field is taken and submitted to the server through form tag. The "submit" button is used to initiate form data submit to the server. You can also use JavaScript code for submitting the form. For example if your form name is "loginForm" then following JavaScript code can be called for submitting the form programmatically.

HTML формы — сложные элементы интерфейса. Они включают в себя разные функциональные элементы: поля ввода и , списки , подсказки и т.д. Весь код формы заключается в элемент .

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

Элемент создаёт надписи к полям формы. Существует два способа группировки надписи и поля. Если поле находится внутри элемента , то атрибут for указывать не нужно.

Last Name Last Name Last Name

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

Контактная информация Имя E-mail
Рис. 1. Группировка полей формы

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

Обязательные для заполнения поля также необходимо выделять. До появления HTML5 использовался символ звездочки * , установленный возле названия поля. В новой спецификации появился специальный атрибут required , который позволяет отметить обязательное поле на уровне разметки. Этот атрибут дает указание браузеру (при условии, что тот поддерживает HTML5), указание не отправлять данные после нажатия пользователем кнопки отправить, пока указанные поля не заполнены.

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

Input:focus { background: #eaeaea; }

Ещё один полезный html5-атрибут — атрибут autofocus . Он позволяет автоматически установить фокус на нужном начальном поле для элементов и (только в один элемент каждой формы).

Пример создания формы регистрации Регистрация Имя Пол мужской женский E-mail Страна Выберите страну проживания Россия Украина Беларусь Отправить

Примечание
action="form.php" — ссылка на файл обработчика формы. Создайте файл в кодировке UTF-8, закачайте его на сервер и замените action="form.php" на путь к файлу на вашем сервере.


Рис. 2. Внешний вид формы по умолчанию

Как видно из рисунка, каждый элемент формы имеет стили браузера по умолчанию. Очистим стили и оформим элементы формы.

Form-wrap { width: 550px; background: #ffd500; border-radius: 20px; } .form-wrap *{transition: .1s linear} .profile { width: 240px; float: left; text-align: center; padding: 30px; } form { background: white; float: left; width: calc(100% - 240px); padding: 30px; border-radius: 0 20px 20px 0; color: #7b7b7b; } .form-wrap:after, form div:after { content: ""; display: table; clear: both; } form div { margin-bottom: 15px; position: relative; } h1 { font-size: 24px; font-weight: 400; position: relative; margin-top: 50px; } h1:after { content: "\f138"; font-size: 40px; font-family: FontAwesome; position: absolute; top: 50px; left: 50%; transform: translateX(-50%); } /********************** стилизация элементов формы **********************/ label, span { display: block; font-size: 14px; margin-bottom: 8px; } input, input { border-width: 0; outline: none; margin: 0; width: 100%; padding: 10px 15px; background: #e6e6e6; } input:focus, input:focus { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio label { position: relative; padding-left: 50px; cursor: pointer; width: 50%; float: left; line-height: 40px; } .radio input { position: absolute; opacity: 0; } .radio-control { position: absolute; top: 0; left: 0; height: 40px; width: 40px; background: #e6e6e6; border-radius: 50%; text-align: center; } .male:before { content: "\f222"; font-family: FontAwesome; font-weight: bold; } .female:before { content: "\f221"; font-family: FontAwesome; font-weight: bold; } .radio label:hover input ~ .radio-control, .radiol input:focus ~ .radio-control { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio input:checked ~ .radio-control { color: red; } select { width: 100%; cursor: pointer; padding: 10px 15px; outline: 0; border: 0; background: #e6e6e6; color: #7b7b7b; -webkit-appearance: none; /*убираем галочку в webkit-браузерах*/ -moz-appearance: none; /*убираем галочку в Mozilla Firefox*/ } select::-ms-expand { display: none; /*убираем галочку в IE*/ } .select-arrow { position: absolute; top: 38px; right: 15px; width: 0; height: 0; pointer-events: none; /*активизируем показ списка при нажатии на стрелку*/ border-style: solid; border-width: 8px 5px 0 5px; border-color: #7b7b7b transparent transparent transparent; } button { padding: 10px 0; border-width: 0; display: block; width: 120px; margin: 25px auto 0; background: #60e6c5; color: white; font-size: 14px; outline: none; text-transform: uppercase; } /********************** добавляем форме адаптивность **********************/ @media (max-width: 600px) { .form-wrap {margin: 20px auto; max-width: 550px; width:100%;} .profile, form {float: none; width: 100%;} h1 {margin-top: auto; padding-bottom: 50px;} form {border-radius: 0 0 20px 20px;} }

Файл form.php

Примечание
В переменной $subject укажите текст, который будет отображаться как заголовок письма;
Ваше_имя — здесь вы можете указать имя, которое будет отображаться в поле «от кого письмо» ;
url_вашего_сайта замените на адрес сайта с формой регистрации;
ваш_email замените на ваш адрес электронной почты;
$headers .= "Bcc: ваш_email". "\r\n"; отправляет скрытую копию на ваш адрес электронной почты.