【问题标题】:Form Validation Vanilla JS表单验证 Vanilla JS
【发布时间】:2016-10-12 00:18:15
【问题描述】:

我正在构建一个多页表单,但我有一些不寻常的验证要求。以下是我想做的事情/到目前为止我所做的事情。

我想做什么:

(1) 在填写每个表单字段时,我希望运行一个函数并检查用户输入是否满足某些条件 - 即对于名字和姓氏,没有数字并且有空格在名字之间。

(2) 一旦每个字段都填满并作为 true 传递,我希望运行另一个函数,重新启用以前禁用的“下一步”按钮,该按钮会将用户移动到表单的下一页。

我做了什么

(1) 创建了一个带有两个输入的迷你版表单:

  1. 包含名字、空格和姓氏的名称
  2. 取电话号码的设置方式如下 xxx xxx xxx

(2) 我已经console.logged 带有通过/失败逻辑的结果,因此我知道用户何时输入某些内容,代码正在正确验证。

我被困在哪里:

我不知道如何创建辅助代码来重新启用之前禁用的“下一步”按钮,该按钮会将表单移动到下一页。

我想做的是,当“下一步”按钮重新启用并单击时,它自己的onclick 功能隐藏当前页面,在序列中查找下一页并更改其@987654323 @ 并且我相信我已经单独编写了该代码,但我不知道如何将它与我的其他需求集成。

function checkForm()
{
	var firstName = document.getElementById("name").value;
	
	var phone = document.getElementById("phone").value;
	

	
	function checkFirstName()
	{
		if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
	{
		console.log("Put a first Name and Last Name");
	}
	else
	{
		console.log("Thank You");
	}

	};
	
	checkFirstName();
	
	function checkPhoneNumber()
	{
		if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
			 {
			 console.log("Please Put in a proper phone number");
			 }
	else
	{
		console.log("Thank you");
		cansubmit = true;
	}
	};
	checkPhoneNumber();
	
};


	
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
	<br />

	Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
	<br />
	
	<button id="myButton" disabled="disabled">Test Me</button>
</form>

【问题讨论】:

    标签: javascript html forms validation


    【解决方案1】:

    见下面的代码。

    在 keyup 上使用而不是 onblur 可能对用户更友好,因为我认识的大多数用户会尝试单击禁用的按钮,而不是按 Tab 或专注于另一个元素。

    function checkForm() {
      var firstName = document.getElementById("name").value;
    
      var phone = document.getElementById("phone").value;
    
      var phoneCanSubmit, nameCanSubmit = false;
    
      function checkFirstName() {
        if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
          nameCanSubmit = false;
          console.log("Put a first Name and Last Name");
        } else {
          nameCanSubmit = true;
          console.log("Thank You");
        }
    
      };
    
      checkFirstName();
    
      function checkPhoneNumber() {
        if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
          phoneCanSubmit = false;
          console.log("Please Put in a proper phone number");
        } else {
          phoneCanSubmit = true;
          console.log("Thank you");
          cansubmit = true;
        }
      };
      checkPhoneNumber();
      if (nameCanSubmit && phoneCanSubmit) {
        document.getElementById("myButton").disabled = false;
      } else {
        document.getElementById("myButton").disabled = true;
      }
    };
    <form>
      First Name:
      <input type="text" id="name" onblur="checkForm()" />
      <label id="nameErrorPrompt"></label>
      <br />Phone Number:
      <input type="text" id="phone" onblur="checkForm()" />
      <label></label>
      <br />
    
      <button id="myButton" disabled="disabled">Test Me</button>
    </form>

    【讨论】:

      【解决方案2】:

      下面的代码给你你想要的。我删除了一些无关检查以简化代码,还将事件处理程序从 HTML 移至 JavaScript。我还将字段检查从较大的 checkForm 函数中提取出来。这为您提供了灵活性,可以在需要时一次使用一个。

      window.addEventListener('load', function(e) {
          var nameInput = document.getElementById('name');
          var phoneInput = document.getElementById('phone');
          var myButton = document.getElementById('myButton');
      
           myButton.addEventListener('click', function(e) {
              e.preventDefault(); //Stop the page from refreshing
               getNextPage('Next page shown!!');
          }, false);
      
          nameInput.addEventListener('blur', function(e) {
              checkName(this.value);
          }, false);
      
          phoneInput.addEventListener('blur', function(e) {
              //Uncomment below to make this responsible only for checking the phone input
              //checkPhoneNumber(this.value);
              /*You could do away with diasbling and check the form 
              on submit, but if you want to keep the disable logic
              check the whole form on the blur of the last item*/
              checkForm();
          }, false);
      }, false);
      
      function getNextPage(foo) {
          console.log('Callback fired: ', foo);
          //Do something here
      }
      
      function checkPhoneNumber(phone) {
          if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
               console.log("Please Put in a proper phone number");
              return 0;
          }
          else {
              console.log("Thank you name entered");
              return 1;
          }
      };
      
      //Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
      function checkName(firstAndLastName) {
          if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
              console.log("Put a first Name and Last Name");
              return 0;
          }
          else {
              console.log("Thank You phone entered");
              return 1;
          }
      
      };
      
      function checkForm() {
          var validCount = 0;
          fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
          var phoneNum = document.getElementById('phone').value;
          var name = document.getElementById('name').value;
          var myButton = document.getElementById('myButton');
      
          validCount += checkPhoneNumber(phoneNum);
          validCount += checkName(name);
          console.log(validCount + ' of ' + fieldCount + ' fields are valid');
          if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs 
              myButton.disabled = false;
          }
          else {
              myButton.disabled = true;
          }
      }
      

      HTML

      <form>
          First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
          <br />
          Phone Number: <input type="text" id="phone" /><label></label>
          <br />
      
          <button id="myButton" disabled="disabled">Test Me</button>
      </form>
      

      【讨论】:

        【解决方案3】:

        如何让每个输入的 onblur 返回一个布尔值,指示该字段是否有效。

        然后在 checkForm 函数中设置一个 cansubmit 变量 (= checkName && checkPhone) 并在此之后继续 - 然后您不需要启用和禁用按钮。

        如果你真的想让按钮启用,你可以使用相同的模式,但是这样做

        document.getElementById("myButton").disabled = !canSubmit;
        

        而且你总是想像现在一样在字段模糊上调用 checkForm。

        另请注意,您现在没有在本地确定 canSubmit 的范围。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-21
          • 2020-11-15
          • 2020-07-07
          • 1970-01-01
          • 2020-12-31
          • 2019-06-27
          • 2019-09-25
          • 2016-01-06
          相关资源
          最近更新 更多