Angular form is $valid when all inputs are blank, why?

岁酱吖の 提交于 2019-12-01 04:21:12

You should place ng-model on each field to enable form on each field, Unless you add ng-model & name with value your field will never considered as part of your form. And do change one thing create one parent variable such as form & add all the scope variables in it. like in controller do $scope.form = {}; & then on UI add all ng-model s to it like form.email, form.password & form.confirmation.

For more better form validation remove action & method attribute from a form & use ng-submit directive which will call one of controller method. & Do call post from that controller method by checking form is $valid or not.

Markup

<form name="signUpForm" ng-submit="submit(signUpForm, form)" novalidate>
    <fieldset>
        <div class="field input-field">
            Email
            <br />
            <input type="email" name="email" ng-model="form.email" required />
        </div>

        <div class="field input-field">
            Password
            <br />
            <input type="password" ng-model="form.password" name="password" required />
        </div>

        <div class="field input-field">
            Confirm Password
            <br />
            <input type="password" ng-model="form.confirmation" name="confirmation" required />
        </div>

        !! -- Form valid? {{signUpForm.$valid}} -- !!

        <div class="actions">
            <input type="submit" value="Sign Up" />
        </div>
    </fieldset>
</form>

Controller

$scope.submit = function(form, formData) {
    if (form.$valid) { //submit form if it is valid
        $http.post('/url', {
          data: formData
        })
        .success(function() {
          //code here
        })
        .error(function() {
        })
    } else {
        alert("Please fill all required fields")
    }     
}

Hope this has cleared your little concept about form, Thanks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!