【问题标题】:AngularJS - submit form programmatically after validationAngularJS - 验证后以编程方式提交表单
【发布时间】:2017-08-03 02:42:48
【问题描述】:

我最近开始研究 AngularJS 1.6。

我正在尝试以编程方式提交表单。原因是我想验证几个字段(必填字段验证)。我花了很多精力(可能是 3-4 小时)试图完成这项工作,但是关于堆栈溢出或 AngularJS 文档的现有答案今天似乎对我有用(奇怪),因此我将其发布为最后的手段.

下面是我的html

<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
    <div>
        {{message}}
    </div>
    <div>
        <label>User Name</label>
        <input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" />
    </div>
    <div>
        <label>Password</label>
        <input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" />
    </div>
    <div>
        <input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" />
    </div>
</form>

我的角码

var demoApp = angular.module('demoApp', []);

demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {   

    $scope.loginUser = function () {

        var form = document.getElementById("loginform");
        //var form = $scope.loginform; - tried this here...
        //var form = $scope["#loginform"]; tried this
        //var form = angular.element(event.target); - tried this...
        // tried a lot of other combinations as well...

        form.attr("method", "post");
        form.attr("action", "Home/Index");
        form.append("UserName", $scope.user.UserName);
        form.append("Password", $scope.user.Password);
        form.append("RememberMe", false);
        form.submit();
    };
}]);

我不断收到错误“attr”不是函数。

我只需要使用 post 方法提交带有值的表单。就在此之前,我试图拦截提交调用并检查验证。

我也愿意尝试任何其他方法。比如把输入类型从submit改成button。将输入放在表单之外。如果验证和提交两者都可以以任何方式发生,我会非常高兴。我只是希望它在客户端验证后发回值,然后服务器将处理重定向。

注意:我希望表单进行完整的回发,以便将其重定向到另一个表单。 (我知道我可以使用 Ajax,但改天可能会!)

【问题讨论】:

  • 你需要什么验证
  • @bharatsavani savani 简单的必填字段验证,现在
  • 好的,首先在你的 loginuser 函数中删除 form.attr 在表单标签中添加操作
  • 就是这样做的,它回发,但不携带模型值。
  • 我应该手动附加表单字段吗?

标签: javascript html angularjs asp.net-mvc postback


【解决方案1】:

首先避免使用var form = document.getElementById("loginform");。您可以使用以下代码,而不是使用 form.submit。以有角度的方式来干杯:D

$scope.loginUser = function () {
  if($scope.loginform.$valid){
      user.rememberme=false;

       $http({
         url: 'Home/Index',
         method: "POST",
         data: user 
    })
    .then(function(response) {
        // success
    }, 
     function(response) { // optional
        // failed
    });

  }
};

【讨论】:

  • 我只能按照我的方式进行操作(最后......呸),因为采用有角度的方式需要我更改后端 C# 代码,这是应该避免的。我知道这不是有角度的方式,但我猜那是另一次了。我正在从事的项目不是 SPA。我会喜欢它成为一个 SPA 并且会从此过上幸福的生活。 :D 干杯!
【解决方案2】:

这是一个验证代码,如果验证未完成按钮未启用

<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
    {{message}}
</div>
<div>
    <label>User Name</label>
    <input type="text" id="txtUserName" required ng-model="user.UserName" name="UserName" />
</div>
<div>
    <label>Password</label>
    <input type="text" id="txtPassword" ng-model="Password" name="user.Password"required />
</div>
<div>
    <input type="submit"  ng-disabled="myForm.UserName.$invalid || myForm.Password.$invalid" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>

【讨论】:

  • 我已经检查过了,禁用了按钮方法。我会接受它作为最后的选择。因为我的应用程序用户习惯点击按钮并看到验证被触发。我不想尽可能长时间地改变这种行为。
  • 您已经制作了一个手动 javascript 函数来验证您的验证并向用户显示
  • 好的,如果这是唯一的方法,那么我可能会朝那个方向努力。
  • 在javascript中创建一个验证和检查所有输入值的功能
  • 如果您对我的回答@DevrajGadhavi 感到满意,请为我投票
【解决方案3】:

您应该在尝试访问表单时使用 $scope,例如 $scope.loginform。但...... 看看 ng-messages。下面是一个在表单中使用 ng-messages 的示例:

<form id="loginform" name="loginform" ng-submit="loginUser()">
    <div>
        {{message}}
    </div>
    <div>
        <label>User Name</label>
        <input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" required/>
        <div class="help-block" ng-messages="loginform.txtUserName.$error" ng-show="loginform.txtUserName.$touched">
            <p ng-message="required">Username is required.</p>
        </div>
    </div>
    <div>
        <label>Password</label>
        <input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" required/>
        <div class="help-block" ng-messages="loginform.txtPassword.$error" ng-show="loginform.txtPassword.$touched">
            <p ng-message="required">Password is required.</p>
        </div>
    </div>
    <div>
        <input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" ng-click="loginUser()" />
    </div>
</form>

添加 ngMessages:

var demoApp = angular.module('demoApp', ['ngMessages']);

demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {   

    $scope.loginUser = function () {
      if($scope.loginform.$valid){
        //Code to run before submitting (but not validation checks)
      } else{
         return false;
     }
    };
}]);

不要忘记在您的应用声明中包含 ngMessages 并包含 ngMessages.js 脚本文件。请注意如何简单地使用 HTML5 验证器。

【讨论】:

  • 禁用按钮方法将是最后的选择。因为我的应用程序用户习惯点击按钮并看到验证被触发。我不想尽可能长时间地改变他们的行为。
  • 我肯定会尝试使用 ngMessages 看看会发生什么。
  • 查看编辑,将提交按钮更改为带有 ngClick 的常规按钮,如果表单有效,则提交表单。
  • 试过了,它的回发,但没有在后端获取表单值。验证都没有被解雇。控制台中没有错误:(
  • 我也尝试了您的最新编辑。在我的情况下没有运气......谢谢你的帮助@garethb,我在其他地方找到了我需要的东西。
【解决方案4】:

我找到了我要找的东西。最后,我必须创建一个用于验证然后提交的指令。所以我在这里发布它作为一个完整的答案。

我的 HTML

<div ng-controller="homeController" ng-init="construct()">    
    <form method="post" action="Index" role="form" id="loginform" name="loginform" ng-form-commit novalidate class="ng-pristine ng-invalid ng-invalid-required">
        <div class="form-group">
            <label for="UserName">User ID</label>
            <input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
                   id="UserName" name="UserName" ng-model="user.UserName" type="text" value=""
                   ng-change="userNameValidation = user.UserName.length == 0">
            <span class="field-validation-error text-danger" ng-show="userNameValidation">The User ID field is required.</span>
        </div>

        <div class="form-group">
            <label for="Password">Password</label>
            <input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
                   id="Password" name="Password" ng-model="user.Password" type="password" value=""
                   ng-change="passwordValidation = user.Password.length == 0">
            <span class="field-validation-error text-danger" ng-show="passwordValidation">The Password field is required.</span>
        </div>

        <div>
            <input type="button" id="btnLogin" title="Login" name="btnLogin" value="Login" ng-click="validateUser(loginform)" />
        </div>
    </form>
</div>

在表单元素上查找 ng-form-commit。这是我创建的指令。

我的 Angular 代码

var demoApp = angular.module('demoApp', []);

demoApp.factory("commonService", function () {
    return {
        isNullOrEmptyOrUndefined: function (value) {
            return !value;
        }
    };
});

//This is the directive that helps posting the form back...
demoApp.directive("ngFormCommit", [function () {
    return {
        require: "form",
        link: function ($scope, $el, $attr, $form) {
            $form.commit = function () {
                $el[0].submit();
            };
        }
    };
}]);

demoApp.controller("homeController", ["$scope", "commonService", function ($scope, commonService) {

    $scope.construct = function construct() {
        $scope.user = { UserName: "", Password: "" };
    };

    $scope.userNameValidation = false;
    $scope.passwordValidation = false;
    $scope.isFormValid = false;

    $scope.validateUser = function ($form) {
        $scope.isFormValid = true;

        $scope.userNameValidation = commonService.isNullOrEmptyOrUndefined($scope.user.UserName);
        $scope.passwordValidation = commonService.isNullOrEmptyOrUndefined($scope.user.Password);

        $scope.isFormValid = !($scope.userNameValidation || $scope.passwordValidation);

        if ($scope.isFormValid === true) {
            $scope.loginUser($form);
        }
    };

    $scope.loginUser = function ($form) {
        $form.commit();
    };
}]);

我找到了指令here

【讨论】:

    【解决方案5】:

    使用 Angular 1.5 组件的示例。

    (function(angular) {
      'use strict';
    
      function DemoFormCtrl($timeout, $sce) {
        var ctrl = this;
        this.$onInit = function() {
          this.url = $sce.trustAsResourceUrl(this.url);
          /*$timeout(function() {
            ctrl.form.$$element[0].submit();
          });*/
        };
    
        this.validate = function(ev) {
          console.log('Running validation.');
          if (!this.form) {
            return false;
          }
        };
      }
    
      angular.module('app', [])
        .component('demoForm', {
          template: `
          <p>To run this demo allow pop-ups from https://plnkr.co</p>
          <hr>
          <p>AngularJS - submit form programmatically after validation</p>
          <form name="$ctrl.form" method="get" target="blank" action="{{::$ctrl.url}}" novalidate
           ng-submit="$ctrl.validate($event)">
            <input type='hidden' name='q' ng-value='::$ctrl.value'>
            <input type='hidden' name='oq' ng-value='::$ctrl.value'>
            <input type="submit" value="submit...">
          </form>`,
          controller: DemoFormCtrl,
          bindings: {
            url: '<',
            value: '<'
          }
        });
    
    })(window.angular);
    

    https://plnkr.co/edit/rrruj6vlWrxpN3od9YAj?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 2010-11-22
      • 1970-01-01
      • 2018-06-13
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多