仅当一个或多个字段包含数字Angular.JS时才验证表单

时间:2022-11-23 13:00:42

I want to validate an order form with Angular.JS.

我想用Angular.JS验证订单。

The form dynamically adds input fields depending on how many products there are.

表单根据产品的数量动态添加输入字段。

The dynamically added input fields are used to determine how many products the user wants to purchase.

动态添加的输入字段用于确定用户想要购买的产品数量。

I want the form to validate if either one of the fields has a value of minimum 1 (the user has to choose at least one product in order to send the form).

我希望表单验证其中一个字段是否具有最小值1(用户必须选择至少一个产品才能发送表单)。

The issue I am having is that I cannot work out how the conditional validation "if one field has a value greater than 0 the form is valid".

我遇到的问题是,我无法弄清楚条件验证如何“如果一个字段的值大于0,则表单有效”。

If I put in min='1' as an attribute for the input field, both field needs to have a value of 1 in order for the form to work.

如果我输入min ='1'作为输入字段的属性,则两个字段都需要值为1才能使表单正常工作。

If I have a placeholder="0" the input fields has a value and therefore will validate the form as long as the other fields are valid.

如果我有一个占位符=“0”,则输入字段具有值,因此只要其他字段有效,就会验证表单。

My idea which I do not know how to implement (or if it's smart) is to check the products total sum is greater than 0.

我不知道如何实现(或者如果它是聪明的)的想法是检查产品总和是否大于0。

Obviously I am a newbie and use a lot of resources online to implement functionality I want to have.

显然我是一个新手,并在线使用大量资源来实现我想要的功能。

HTML

HTML

<form id="orderForm" name="orderForm" role="form" ng-submit="submitForm(orderForm.$valid)" class="orderForm" ng-controller="formController as formCtrl" novalidate>

    <table class="table">
        <thead>
            <tr>
                <th scope="col">Produkt</th>
                <th scope="col">Antal</th>
                <th scope="col" class="text-right">Pris</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in formCtrl.products">
                <td>
                    <img ng-src="{{product.images.thumb}}" alt="{{product.name}}">
                    <h6 class="d-inline-block">{{product.name}} <small class="d-block">{{product.description}}</small></h6>
                </td>
                <td>

                    <input type="number" class="form-control" ng-model="product.quantity" name="{{'quantity' + product.productId}}" min="0" max="99" required>

                </td>
                <td class="text-right">
                    {{product.price | currency : "SEK"}}
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" class="text-right">
                    <h5 class="d-inline-block">Totalt: <em ng-bind="sumCalc(product.price) | currency : 'SEK'"></em></h5>
                </td>
            </tr>
        </tfoot>
    </table>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputEmail">Email</label>
            <input name="email" ng-model="formCtrl.email" type="email" class="form-control" id="inputEmail" placeholder="Email" required>
            <div ng-show="orderForm.email.$invalid && !orderForm.email.$pristine" class="invalid-feedback">
                Vänligen fyll i en korrekt email
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputFirstName">Förnamn</label>
            <input name="firstname" ng-model="formCtrl.fName" type="text" class="form-control" id="inputFirstName" placeholder="Förnamn" required>
            <div ng-show="orderForm.fName.$invalid && !orderForm.fName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt förnamn
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputLastName">Efternamn</label>
            <input name="lastname" ng-model="formCtrl.lName" type="text" class="form-control" id="inputLastName" placeholder="Efternamn" required>
            <div ng-show="orderForm.lName.$invalid && !orderForm.lName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt efternamn
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputStreet">Gatuadress</label>
            <input name="street" ng-model="formCtrl.street" type="text" class="form-control" id="inputStreet" placeholder="Gatuadress" required>
            <div ng-show="orderForm.street.$invalid && !orderForm.street.$pristine" class="invalid-feedback">
                Vänligen fyll i din gatuaddress
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputZip">Postnr</label>
            <input name="zip" ng-model="formCtrl.zip" type="text" class="form-control" id="inputZip" placeholder="Postnummer" required>
            <div ng-show="orderForm.zip.$invalid && !orderForm.zip.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt postnummer
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputTown">Stad</label>
            <input name="town" ng-model="formCtrl.town" type="text" class="form-control" id="inputTown" placeholder="Stad" required>
            <div ng-show="orderForm.town.$invalid && !orderForm.town.$pristine" class="invalid-feedback">
                Vänligen fyll i din stad
            </div>
        </div>
    </div>

    <div> orderForm is {{orderForm.$valid}}</div>

    <div class="form-group">
        <button type="submit" class="btn btn-default" id="inputSubmitButton" ng-disabled="orderForm.$invalid && inputQuantity.">Skicka</button>

    </div>
</form>

controllers.js

controllers.js

var app = angular.module('controllers', []);
app.controller('formController', function($scope) {

    this.products = product;
    $scope.submitForm = function(isValid) {
        // check to make sure the form is completely valid
        if (isValid) {
            alert('our form is amazing');
        }

    };

    $scope.sumCalc = function() {
        var sum = 0;
        angular.forEach(product, function(product, index) {
            sum += parseInt(product.quantity, 10) * product.price;

        });
        return sum;
        //totalPrice = sum;
    };
});

var product = [{
        name: 'asd',
        productId: 01,
        price: 100,
        description: 'asd',
        specification: "asd",
        images: {
            full: 'asd',
            thumb: 'asd'
        },
        quantity: 0
    },
    {
        name: "asd",
        productId: 02,
        price: 100,
        description: "asd",
        specification: "asd",
        images: {
            full: 'asd',
            thumb: 'asd'
        },
        quantity: 0
    }
];
var app = angular.module('controllers', []);
app.controller('formController', function($scope) {

    this.products = product;
    $scope.submitForm = function(isValid) {
        // check to make sure the form is completely valid
        if (isValid) {
            alert('our form is amazing');
        }

    };

    $scope.sumCalc = function() {
        var sum = 0;
        angular.forEach(product, function(product, index) {
            sum += parseInt(product.quantity, 10) * product.price;

        });
        return sum;
        //totalPrice = sum;
    };
});

var product = [{
        name: 'asd',
        productId: 01,
        price: 100,
        description: 'asd',
        specification: "asd",
        images: {
            full: 'asd',
            thumb: 'asd'
        },
        quantity: 0
    },
    {
        name: "asd",
        productId: 02,
        price: 100,
        description: "asd",
        specification: "asd",
        images: {
            full: 'asd',
            thumb: 'asd'
        },
        quantity: 0
    }
];

1 个解决方案

#1


0  

Edit your HTML as following:

按以下方式编辑HTML:

<form id="orderForm" name="orderForm" role="form" ng-submit="submitForm(orderForm.$valid)" class="orderForm" ng-controller="formController as formCtrl" novalidate>

    <table class="table">
        <thead>
            <tr>
                <th scope="col">Produkt</th>
                <th scope="col">Antal</th>
                <th scope="col" class="text-right">Pris</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in formCtrl.products">
                <td>
                    <img ng-src="{{product.images.thumb}}" alt="{{product.name}}">
                    <h6 class="d-inline-block">{{product.name}} <small class="d-block">{{product.description}}</small></h6>
                </td>
                <td>

                    <input type="number" class="form-control" ng-model="product.quantity" name="{{'quantity' + product.productId}}" min="0" max="99" required>

                </td>
                <td class="text-right">
                    {{product.price | currency : "SEK"}}
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" class="text-right">
                    <h5 class="d-inline-block">Totalt: <em ng-bind="sumCalc(product.price) | currency : 'SEK'"></em></h5>
                </td>
            </tr>
        </tfoot>
    </table>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputEmail">Email</label>
            <input name="email" ng-model="formCtrl.email" type="email" class="form-control" id="inputEmail" placeholder="Email" required>
            <div ng-show="orderForm.email.$invalid && !orderForm.email.$pristine" class="invalid-feedback">
                Vänligen fyll i en korrekt email
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputFirstName">Förnamn</label>
            <input name="firstname" ng-model="formCtrl.fName" type="text" class="form-control" id="inputFirstName" placeholder="Förnamn" required>
            <div ng-show="orderForm.fName.$invalid && !orderForm.fName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt förnamn
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputLastName">Efternamn</label>
            <input name="lastname" ng-model="formCtrl.lName" type="text" class="form-control" id="inputLastName" placeholder="Efternamn" required>
            <div ng-show="orderForm.lName.$invalid && !orderForm.lName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt efternamn
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputStreet">Gatuadress</label>
            <input name="street" ng-model="formCtrl.street" type="text" class="form-control" id="inputStreet" placeholder="Gatuadress" required>
            <div ng-show="orderForm.street.$invalid && !orderForm.street.$pristine" class="invalid-feedback">
                Vänligen fyll i din gatuaddress
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputZip">Postnr</label>
            <input name="zip" ng-model="formCtrl.zip" type="text" class="form-control" id="inputZip" placeholder="Postnummer" required>
            <div ng-show="orderForm.zip.$invalid && !orderForm.zip.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt postnummer
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputTown">Stad</label>
            <input name="town" ng-model="formCtrl.town" type="text" class="form-control" id="inputTown" placeholder="Stad" required>
            <div ng-show="orderForm.town.$invalid && !orderForm.town.$pristine" class="invalid-feedback">
                Vänligen fyll i din stad
            </div>
        </div>
    </div>

    <div> orderForm is {{orderForm.$valid}}</div>

    <div class="form-group">
        <button type="submit" class="btn btn-default" id="inputSubmitButton" ng-disabled="orderForm.$invalid || !checkProductSelected()">Skicka</button> <!--Pay attention to the 'ng-disabled' binding-->

    </div>
</form>

and modify your Javascript to look like this:

并修改您的Javascript看起来像这样:

app.controller('formController', function($scope) {

    this.products = product;
    $scope.submitForm = function(isValid) {
    // check to make sure the form is completely valid
    if (isValid) {
      alert('our form is amazing');
    }

    };

    $scope.sumCalc = function() {
    var sum = 0;
    angular.forEach(product, function(product, index) {
      sum += parseInt(product.quantity, 10) * product.price;

    });
    return sum;
    //totalPrice = sum;
    };


    //***The following function is added to your original code***
    $scope.checkProductSelected = function() {

        var sum = 0;

        angular.forEach(product, function(product, index) {

            sum += parseInt(product.quantity, 10) * product.price;
        });

        return sum > 0;
    }
});

Look for the comments in the code to see what has been added or edited. (On HTML it's after your submit button)

在代码中查找注释以查看已添加或编辑的内容。 (在HTML上,它是在你的提交按钮之后)

#1


0  

Edit your HTML as following:

按以下方式编辑HTML:

<form id="orderForm" name="orderForm" role="form" ng-submit="submitForm(orderForm.$valid)" class="orderForm" ng-controller="formController as formCtrl" novalidate>

    <table class="table">
        <thead>
            <tr>
                <th scope="col">Produkt</th>
                <th scope="col">Antal</th>
                <th scope="col" class="text-right">Pris</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in formCtrl.products">
                <td>
                    <img ng-src="{{product.images.thumb}}" alt="{{product.name}}">
                    <h6 class="d-inline-block">{{product.name}} <small class="d-block">{{product.description}}</small></h6>
                </td>
                <td>

                    <input type="number" class="form-control" ng-model="product.quantity" name="{{'quantity' + product.productId}}" min="0" max="99" required>

                </td>
                <td class="text-right">
                    {{product.price | currency : "SEK"}}
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" class="text-right">
                    <h5 class="d-inline-block">Totalt: <em ng-bind="sumCalc(product.price) | currency : 'SEK'"></em></h5>
                </td>
            </tr>
        </tfoot>
    </table>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputEmail">Email</label>
            <input name="email" ng-model="formCtrl.email" type="email" class="form-control" id="inputEmail" placeholder="Email" required>
            <div ng-show="orderForm.email.$invalid && !orderForm.email.$pristine" class="invalid-feedback">
                Vänligen fyll i en korrekt email
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputFirstName">Förnamn</label>
            <input name="firstname" ng-model="formCtrl.fName" type="text" class="form-control" id="inputFirstName" placeholder="Förnamn" required>
            <div ng-show="orderForm.fName.$invalid && !orderForm.fName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt förnamn
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputLastName">Efternamn</label>
            <input name="lastname" ng-model="formCtrl.lName" type="text" class="form-control" id="inputLastName" placeholder="Efternamn" required>
            <div ng-show="orderForm.lName.$invalid && !orderForm.lName.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt efternamn
            </div>
        </div>
    </div>

    <div class="form-row">
        <div class="col-md-4 mb-3">
            <label for="inputStreet">Gatuadress</label>
            <input name="street" ng-model="formCtrl.street" type="text" class="form-control" id="inputStreet" placeholder="Gatuadress" required>
            <div ng-show="orderForm.street.$invalid && !orderForm.street.$pristine" class="invalid-feedback">
                Vänligen fyll i din gatuaddress
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputZip">Postnr</label>
            <input name="zip" ng-model="formCtrl.zip" type="text" class="form-control" id="inputZip" placeholder="Postnummer" required>
            <div ng-show="orderForm.zip.$invalid && !orderForm.zip.$pristine" class="invalid-feedback">
                Vänligen fyll i ditt postnummer
            </div>
        </div>

        <div class="col-md-4 mb-3">
            <label for="inputTown">Stad</label>
            <input name="town" ng-model="formCtrl.town" type="text" class="form-control" id="inputTown" placeholder="Stad" required>
            <div ng-show="orderForm.town.$invalid && !orderForm.town.$pristine" class="invalid-feedback">
                Vänligen fyll i din stad
            </div>
        </div>
    </div>

    <div> orderForm is {{orderForm.$valid}}</div>

    <div class="form-group">
        <button type="submit" class="btn btn-default" id="inputSubmitButton" ng-disabled="orderForm.$invalid || !checkProductSelected()">Skicka</button> <!--Pay attention to the 'ng-disabled' binding-->

    </div>
</form>

and modify your Javascript to look like this:

并修改您的Javascript看起来像这样:

app.controller('formController', function($scope) {

    this.products = product;
    $scope.submitForm = function(isValid) {
    // check to make sure the form is completely valid
    if (isValid) {
      alert('our form is amazing');
    }

    };

    $scope.sumCalc = function() {
    var sum = 0;
    angular.forEach(product, function(product, index) {
      sum += parseInt(product.quantity, 10) * product.price;

    });
    return sum;
    //totalPrice = sum;
    };


    //***The following function is added to your original code***
    $scope.checkProductSelected = function() {

        var sum = 0;

        angular.forEach(product, function(product, index) {

            sum += parseInt(product.quantity, 10) * product.price;
        });

        return sum > 0;
    }
});

Look for the comments in the code to see what has been added or edited. (On HTML it's after your submit button)

在代码中查找注释以查看已添加或编辑的内容。 (在HTML上,它是在你的提交按钮之后)