如果输入尚未经过验证,AngularJS会阻止提交

时间:2016-04-29 01:24:56

标签: javascript html angularjs forms

如果输入尚未经过验证,我试图阻止表单提交..

这是我的代码:

HTML

<form method="post" enctype="multipart/form-data" ng-submit="insertCustomer(insertProfile)" id="form-customer" name="form" class="css-form" novalidate >
<div class="row">
    <div class="col-md-7">
        <label>Full Name* 
        <span class="required-label" ng-show="form.$submitted || form.full_name.$touched">
            <span ng-show="form.full_name.$error.required">(Full Name is required.)</span>
        </span>
        </label>
        <input type="text" ng-model="insertProfile.full_name" name="full_name" class="form-control" required="" />
    </div>
</div>
</form>

<button type="submit" form="form-customer"
        class="btn btn-primary pull-right" id="cmd_insert_customer" ng-show="tab == 3">
Insert Customer
</button>

我已尝试使用ng-submit = "form.$valid && insertCustomer(insertProfile)" ...如果输入为空,则表单不会提交但是当我输入值时...它仍然没有提交...... < / p>

2 个答案:

答案 0 :(得分:1)

删除以下内容,因为您将使用Angular Method提交表单。

$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";

此外,ngSubmit仅在某些情况下阻止默认行为。

这是更好的示例https://plnkr.co/edit/a14f9tLmKN48JCDMMpd0?p=preview

答案 1 :(得分:1)

将表单传递给insertCustomer函数并检查函数的有效性

<form method="post" enctype="multipart/form-data" ng-submit="insertCustomer(form)" id="form-customer" name="form" class="css-form" novalidate >
<div class="row">
    <div class="col-md-7">
        <label>Full Name* 
        <span class="required-label" ng-show="form.$submitted || form.full_name.$touched">
            <span ng-show="form.full_name.$error.required">(Full Name is required.)</span>
        </span>
        </label>
        <input type="text" ng-model="insertProfile.full_name" name="full_name" class="form-control" required="" />
    </div>
</div>
</form>

<button type="submit" form="form-customer"
        class="btn btn-primary pull-right" id="cmd_insert_customer" ng-show="tab == 3">
Insert Customer
</button>

并在js中检查如下

$scope.insertCustomer = function(form){
    if(form.$invalid){
        return;
    }
    //form submit code....
}
希望它有效。