Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 30.11.2018, 11:01
Новичок на форуме
Отправить личное сообщение для Alan Посмотреть профиль Найти все сообщения от Alan
 
Регистрация: 30.11.2018
Сообщений: 1

Как вывести ошибки для пользователя?
Добрый день. Подскажите пожалуйста, как можно вывести ошибки при вводе данных пользователя в поля и ошибки при запросах. На данный момент, ошибки отображаются в консоле. Но хотелось бы, чтоб для пользователя они отображались внутри формы (не алертами). p.s. В js я не так силен...

Вот форма.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Firebase Web Quickstart</title>
    <link rel="stylesheet" href="style/style.css">
    <!-- Firebase App is always required and must be first -->
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-app.js"></script>
    <!-- Add additional services that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-messaging.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.9/firebase-functions.js"></script>

  </head>
  <body>

    <div class="container">

      <input id="name" type="text" placeholder="Имя"/>
    </br>

      <input id="surname" type="text" placeholder="Фамилия"/>
    </br>

      <input id="age" type="number" placeholder="Возраст"/>
    </br>

    <select id="gender" type="text" placeholder="gender">
      <option></option>
      <option value="Male">Мужской</option>
      <option value="Female">Женский</option>
    </select>

      <input id="txtEmail" type="email" placeholder="Почта">
    </br>

      <input id="txtPassword" type="password" placeholder="Пароль">
    </br>

      <button id="btnLogin" class="btn btn-action">
        Войти
      </button>

      <button id="btnSingup" class="btn btn-secondary">
        Зарегистрироваться
      </button>

      <button id="btnLogout" class="btn btn-action hide">
        Выйти
      </button>

      <button id="btnReset" class="btn btn-action hide1">
        Восстановить
      </button>

      <script type="text/javascript">
    (function () {

          // Initialize Firebase
          var config = {
              apiKey: "AIzaSyBT4Z6I8O9LlbjTMPyMBE-LWh3karrbXpE",
              authDomain: "new-app-98447.firebaseapp.com",
              databaseURL: "https://new-app-98447.firebaseio.com",
              projectId: "new-app-98447",
              storageBucket: "new-app-98447.appspot.com",
              messagingSenderId: "451825055280"
          };
          firebase.initializeApp(config);
          const auth = firebase.auth();


          //  GET ELEMENTS
          let name = document.getElementById('name');
          let surname = document.getElementById('surname');
          let age = document.getElementById('age');
          let gender = document.getElementById('gender');
          const txtEmail = document.getElementById('txtEmail');
          const txtPassword = document.getElementById('txtPassword');
          const btnLogin = document.getElementById('btnLogin');
          const btnSingup = document.getElementById('btnSingup');
          const btnLogout = document.getElementById('btnLogout');
          const btnReset = document.getElementById('btnReset');
          const dbRef = firebase.database().ref();
          const usersRef = dbRef.child('users');


          usersRef.on("child_added", snap => {
              console.log("This is users", snap.val());
          });

          //  ADD LOGIN EVENT
          btnLogin.addEventListener('click', e => {
              //  GET EMAIL AND PASS
              const email = txtEmail.value;
              const pass = txtPassword.value;
              const auth = firebase.auth();
              //  SING IN
              // console.log("email and password", email, pass, auth);
              const promise = auth.signInWithEmailAndPassword(email, pass);
              promise.then(response => {
                  console.log("This is response", response.user.uid);
                  dbRef.child("users" + response.user.uid).on("child_added", snap => {
                      console.log("My user", snap.val());
                  })
              })
                  .catch(error => console.log(error));
              // promise.catch(e => console.log(e.message));
          });

          //  ADD SINUP EVENT
          btnSingup.addEventListener('click', e => {
              //  GET EMAIL AND PASS
              const email = txtEmail.value;
              const pass = txtPassword.value;
              //  SING IN
              const promise = auth.createUserWithEmailAndPassword(email, pass);
              promise
                  .catch(e => console.log(e.message));

          });

          btnLogout.addEventListener('click', e => {
              firebase.auth().signOut()
                  .then(function (response) {
                      console.log("This is response", response);
                  }, function (error) {
                      console.log("This is error", error);
                  })
          });

          //  ADD REALTIME addEventListener
          firebase.auth().onAuthStateChanged(firebaseUser => {
              if (firebaseUser) {
                  console.log(firebaseUser);
                  console.log("This is user", firebaseUser.uid);
                  let newUser = {};
                  newUser.name = name.value;
                  newUser.surname = surname.value;
                  newUser.age = age.value;
                  newUser.gender = gender.value;
                  userRef = dbRef.child("users" + firebaseUser.uid).push(newUser, response => {
                      console.log("This is user update response", response);
                  });
                  btnLogout.classList.remove('hide');
              } else {
                  console.log(e.message);
                  btnLogout.classList.add('hide');
              }
          });

          // Сброс пароля на почту

          btnReset.addEventListener('click', e => {
            console.log("This is email", txtEmail.value);
              firebase.auth().sendPasswordResetEmail(txtEmail.value)
                  .then(function () {
                      console.log("its send");
                      // Email sent.
                  }).catch(function (error) {
                  console.log("This is error", error);
                  // An error happened.
              });
          });



      }());

      </script>

        <a class="txt-modals"> <a href="login.html">Login</a> \ <a href="register.html">Registration</a></a>
    </div>
  </body>
</html>


Буду благодарен за любую помощь.
Ответить с цитированием
Ответ


Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как вывести свои иконки погоды? spinastr Общие вопросы Javascript 18 01.03.2018 14:07
Как создать цитатник? WGN Общие вопросы Javascript 10 29.01.2017 01:39
Как подключить class к window.location для открытия ссылки в popup окне? Sergey771 Общие вопросы Javascript 0 19.11.2016 12:34
Как подключить полифил для стилей AlexKain Events/DOM/Window 2 01.07.2016 11:25
Как использовать each() для будущих элементов pro_xaoc jQuery 2 25.02.2013 07:12