0

Using angularjs 1.3 and Bootstrap 3 here.

I am trying to validate my form for required field. I added html5 "required" attribute. I also added ng-class to highlight the error but the issue is when the form loads my input field ie texbox is already highlighted. What I am looking for is to hightlight the texbox on button click. Do I have to manually check for this and show error?

I use the below code:

  <div class="m-grid-col-lg-10" 
       ng-class="{ 'has-error': nameForm.userName.$invalid }">
      <input type="text" name="userName" required ng-model="userName"
             class="form-control input-lg input-small" />
  </div>

Button click:

<button class="btn btn-primary" type="button"
        ng-click="done(nameForm.$valid)">
    Done
</button>

JSController code:

 $scope.done = function (isValid) {
        if (isValid) {
            $modalInstance.close();
        }
        else {
            return false;
        }
    };

Here is a jsfiddle:

http://jsfiddle.net/aman1981/a0cLtnpr/7/

1 Answer 1

1
'has-error': nameForm.userName.$invalid && nameForm.userName.$touched

This way the has-error only hapepns if invalid and touched, you can also do or form.$submitted if you want to trigger on submit incase they didn't even touch it.

Updated:

'has-error': nameForm.userName.$invalid && (nameForm.userName.$touched || nameForm.$submitted)
Sign up to request clarification or add additional context in comments.

10 Comments

I added $touched above. Now I dont see my input highlighted on pageload but also I dont see it highlighted when I click on the submit button. Any way to trigger on page submit. I am already returning false so I thought that might trigger. Another thing is that this works when i click on my textbox and then click outside, I can see the required field error.
nothing happens when I click the button. Its only when I click inside the textbox, validation triggers. See updated jsfiddle with your code: jsfiddle.net/aman1981/a0cLtnpr/10
set the button to type="submit" and set ng-submit="done(newForm)" (on form element) and generally I prefer to pass form into the function and check if form.$valid inside of it. But thats a preference. If you dont use ng-submit and type=submit angular doesn't know its been submit by a button click you can cheat, and say newForm.$setSubmitted(); then call done()
Thanks adding type="submit" with ng-submit works for me.
Ng-submit only for form element. If you use button on click to call a function you need to mark the form as form.$setSubmitted() to trigger validation error to appear.
|

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.