Search code examples
javascriptangularjshtmlvalidationrequired

Angular ng-model with required


I'm trying to create a simple input with html5 "required". I'm using placeholder, so I'd like the initial value of the input to be empty. I have the input bound to a ng-model that is initialized as empty (so the placeholder shows). When I go to the page, it shows that input is required for the , which shouldn't show unless the user submits the form and the input is empty. how can I do this:

<input type="text" required ng-model="name">
..in controller:
$scope.name = "";

and not have the form think I am submitting an empty input?


Solution

  • One way of only validating when the user has actually interacted with your input element is to use $dirty to determine wether to show your error message. e.g.

    <span ng-show="form.name.$dirty && form.name.$error.required">
          Name is required
    </span>