使用本地存储数据生成字段时如何删除表单验证错误

Posted

技术标签:

【中文标题】使用本地存储数据生成字段时如何删除表单验证错误【英文标题】:How to remove form validation errors when the fields are generated with localstorage data 【发布时间】:2016-01-29 05:22:33 【问题描述】:

我有这个表格,我正在尝试验证一下。当没有输入时,它应该抛出“这是必需的”消息并禁用提交按钮。它工作正常,如果输入字段为空,它会抛出错误消息。现在我正在做的是将这些表单字段数据保存到浏览器本地存储中,并且当用户尝试再次填写表单时,我正在从本地存储中生成这些字段。但是“这是必需的”消息仍然显示,并且即使在字段预先填充了 cookie 后该按钮也被禁用。我怎样才能解决这个问题?

</script>
      <script src="angular.js"></script>
      <script type="text/javascript">
      function cookies()

    var fieldvalue = document.getElementById('rentname').value;
    var fieldvalue1 = document.getElementById('rentphone').value;
    var fieldvalue2 = document.getElementById('rentaddress').value;

    localStorage.setItem('text',fieldvalue);
    localStorage.setItem('text1',fieldvalue1);
    localStorage.setItem('text2',fieldvalue2);
  

  function load()
    var storedValue = localStorage.getItem('text');
    var storedValue1 = localStorage.getItem('text1');
    var storedValue2 = localStorage.getItem('text2');

    if(storedValue)
      document.getElementById('rentname').value = storedValue;
    

    if(storedValue1)
      document.getElementById('rentphone').value = storedValue1;
    

    if(storedValue2)
      document.getElementById('rentaddress').value = storedValue2;
    
  
</script>


</head>
   <body onload="load()">
      <div class="container">
         <div class="row" style="padding-top:2rem;">
            <div class="col-md-4">
               <h2>Reserve Your Seat</h2>
            </div>
         </div>
         <hr>
         <form ng-app="rentalform" ng-controller="validateCtrl" method="post" id="rentalform" name="rentalform"     action="rentinsertdb.php" novalidate>
           <div class="form-group space" >
              <label for="focusedinput" class="col-sm-2 control-label">Full Name</label>
              <div class="col-sm-8 tabular-border">
                 <input type="text" class="form-control" placeholder="Enter full name" name="rentname" id="rentname" ng-model="rentname" required>
                 <span style="color:red">
                  <span ng-show="!rentname.length">Name is required.</span>
                </span>
              </div>
           </div>
           <div class="form-group space" >
              <label for="focusedinput" class="col-sm-2 control-label">Choose your ride</label>
              <div class="col-sm-8 tabular-border">
                 <div class="dropdown">
                  <select class="btn btn-default dropdown-toggle" name="rentcar" ng-model="rentcar" required>
                    <option value="" disabled selected>Choose your ride</option>
                    <option value="Toyota Alion 2008">Toyota Alion 2008</option>
                    <option value="Toyota Premio 2008">Toyota Premio 2008</option>
                    <option value="Toyota Corolla 2006">Toyota Corolla 2006</option>
                    <option value="Toyota Noah 2010">Toyota Noah 2010</option>
                    <span style="color:red" ng-show="rentalform.rentcar.$dirty && rentalform.rentcar.$invalid">
                 </select>
                 <span style="color:red">
                  <span ng-show="!rentcar.length">Please Select Your Car.</span>
                 </div>
              </div>
           </div>
           <!-- <div class="form-group space" >
              <label for="focusedinput" class="col-sm-2 control-label">Phone Number</label>
              <div class="col-sm-8 tabular-border">
                 <input type="text" class="form-control" id="focusedinput" placeholder="Enter phone number">
              </div>
              <div class="col-sm-2">
                 <p class="help-block"></p>
              </div>
           </div> -->
           <div class="form-group space" >
              <label for="focusedinput" class="col-sm-2 control-label">Phone Number</label>
              <div class="col-sm-8 tabular-border">
                 <input type="text" minlength="11" class="form-control" name="rentphone" placeholder="Enter phone number" ng-model="rentphone" id="rentphone" required>
                 <span style="color:red">
                  <span ng-show="!rentphone.length">Phone Number is Required.</span>
              </div>
              <div class="col-sm-2">
                 <p class="help-block"></p>
              </div>
           </div>
           <div class="form-group space" >
            <label for="focusedinput" class="col-sm-2 control-label">Date</label>
            <div class="col-sm-8 tabular-border">
               <input type="date" class="form-control" id="focusedinput" placeholder="On Which date you would like to rent your ride?" name="rentdate" ng-model="rentdate" required>
               <span style="color:red">
                  <span ng-show="!rentdate.length">Date is Required.</span>
            </div>
            <div class="col-sm-2">
               <p class="help-block"></p>
            </div>
         </div>
           <div class="form-group space" >
            <label for="focusedinput" class="col-sm-2 control-label">Profession</label>
            <div class="col-sm-8 tabular-border">
               <input type="text" class="form-control" id="focusedinput" placeholder="Enter Institution/Profession" name="rentprof">
            </div>
            <div class="col-sm-2">
               <p class="help-block"></p>
            </div>
         </div>
           <div class="form-group space">
              <label for="txtarea1" class="col-sm-2 control-label">Pick up address</label>
              <div class="col-sm-8 tabular-border"><textarea  name="rentaddress" cols="50" rows="4" class="form-control" ng-model="rentaddress" placeholder="Enter Full Address; For example: House#38, Road 7/a, Dhanmondi, Dhaka-1205, Bangladesh" id="rentaddress" required></textarea>

          </div>
          <span style="color:red">
              <span ng-show="!rentaddress.length">Address is Required.</span>
       </div>

       <div class="col-sm-8 col-sm-offset-2 space">
          <button class="btn-primary btn" style="background-color:#03a9f4; border-color:#03a9f4;" id="submitrent" data-toggle="modal" data-target="#myModal" ng-disabled="rentalform.$invalid" onClick="cookies()"> Confirm </button>
       </div>
     </form>
     <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Order Placed!</h4>
    </div>
    <div class="modal-body">
      <p>Your Order Has Been Placed! We will call you shortly!</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    </div>
  </div>

</div>


</div>


 </div>
  <script type="text/javascript">


$("#submitrent").click( function() 
     $.post( $("#rentalform").attr("action"),
     $("#rentalform :input").serializeArray(),
     function(info) $("#result").html(info);
     );
     clearInput();
     );
     $("#rentalform").submit(function() 
        return false;
     );
     function clearInput() 
         $("#rentalform :input").each( function() 
            $(this).val('');
             );
         
  </script>

  <script>
    var app = angular.module('rentalform', []);
    app.controller('validateCtrl', function($scope) 

    );

【问题讨论】:

这似乎不是整个文档。你能清理并完成吗? 其实形式的功能和验证一切都在那里 【参考方案1】:

为什么不利用 angulars 处理表单的能力。你可以试试这个。

Plunker:http://plnkr.co/edit/sQWL0QPFNNsmVh4bXMUH?p=preview

HTML

 <body ng-controller="MainCtrl">
  <form name="myForm" novalidate>
    <label>* First Name</label>
    <input name="firstName" class="input-text" type="text" data-ng-model="user.firstName" required data-ng-class="'required-error':nameError">
    <div data-ng-if="nameError" class="error-msg">First Name is Required</div>
    <br/>

    <input data-ng-click="submit()" type="submit" value="Submit">
    <button data-ng-click="loadLocalData()">Load Local Data</button>
  </form>
</body>

JS

app.controller('MainCtrl', function($scope) 
  $scope.user = 
    firstName: '',
    lastName: ''
  ;
  $scope.nameError = false;

  localStorage.setItem('firstName', 'Harsh');

  $scope.submit = function() 
    if ($scope.myForm.firstName.$valid) 
      $scope.nameError = false;
      // make request here
     else 
      $scope.nameError = true;
    
  ;

  $scope.loadLocalData = function() 
    $scope.user.firstName = localStorage.getItem('firstName');
    $scope.nameError = false;
    $scope.myForm.$setPristine();
  ;
);

说明

    在表单中添加 name 属性并添加 novalidate(将阻止默认验证) AngularJS 将在范围内创建一个具有表单名称的对象(此处为 $scope.myForm) 为输入添加名称属性(将创建名称类似于 $scope.myForm.firstName 的对象) 在提交时进行验证并检查必填字段 重置错误变量并将表单设置为重置或加载本地数据时的原始状态(如果需要) 阅读 angularjs 文档以获取更多信息https://docs.angularjs.org/guide/forms

【讨论】:

【参考方案2】:

您正在更新 Angular 范围之外的字段,因此您必须告诉 Angular 您更新了它。通过使用 Angular 范围内的 LocalStorage 更新字段来强制 $scope.apply()

【讨论】:

以上是关于使用本地存储数据生成字段时如何删除表单验证错误的主要内容,如果未能解决你的问题,请参考以下文章

单击angularjs中的提交表单时如何删除“请填写此字段”弹出但其他验证应该有效

发生验证错误后,如何使用 PrimeFaces AJAX 填充文本字段?

如何使用 jquery 启用表单的提交按钮?

如何在 laravel 中输入所有数组并在字段下方显示验证错误

如何防止所有表单字段在填写单个字段时进行验证

如何删除 Angular 表单组中的特定错误