1

Is there an automated way in Angular to display the error messages for invalid form. For Example, I have the below. It indeed works well in that it doesn't allow the user to submit but it doesn't give the user any automatic feedback to tell them that elements are required. Isn't there an automatic way to get it to print a field is required message by the field if the form is invalid on submit?

           <div class="form-center">
    <form name="loginform" class="forms" ng-controller="controllers.LoginController">
        <fieldset>  <legend><h3>Account Login</h3></legend>

            <div class="advanced-search-item">
                <label>Username:</label><br /> <input type="text" ng-model="username" name="username" placeholder="username" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>

            </div>

            <div class="advanced-search-item">
            <label>Password:</label><br /> 
                <input type="password" name="password" ng-model="password" placeholder="password" required><span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>
            </div>


             <div class="advanced-search-item">
                 <a href="#" class="advanced-search-button submit-button" ng-disabled='!loginform.$valid' ng-click="submitted=true;loginUser()">Login</a>
            </div>


        </fieldset>
    </form>
    </div>

1 Answer 1

2

You will have to add some spans to show errors beside input fields like below

<span class="error" ng-show="submitted && loginform.username.$error.required">Required!</span>

<span class="error" ng-show="submitted && loginform.password.$error.required">Required!</span>

Hopefully you can keep this text in red color, below is the CSS

.error {
    padding-left:10px;
    color: #F00;
}

when form is submitted and if there are errors it will show above spans

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

It seems the submitted variable is set to true already when I get to the form initially... so the span displays immediately... Do I have something setup wrong?
what error do you see in console? Also you need to set submitted=true; when Login link is clicked like ng-click="submitted=true;loginUser()", have you added angualar.js link correctly?
Actually now what happens with the corrected code above is that, it just submits the form anyway and doesn't disable the submit button... No errors in the console at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.