0

I have inputs in a web page without the form tag (useless to me). How can I get their validity status inside the HTML ? This

<input name="myInput" type="text" ng-pattern="/^[0-9]{13}$/">
<input type="button" ng-show="myInput.$valid">

doesn't work.

Luke Skywalker
  • 1,464
  • 3
  • 17
  • 35

1 Answers1

1

I'm afraid that won't work without wrapping it in a form as you need to access those fields via the form's controller.

<form name="myForm">
    <input name="myInput" type="text" ng-pattern="/^[0-9]{13}$/">
    <input type="button" ng-show="myForm.myInput.$valid">
</form>

Should work.

If you're unable to use the form tag for any reason, you'll have to wire that up manually.

ivarni
  • 17,658
  • 17
  • 76
  • 92
  • 1
    For another good reason to use the form tag, see [this](http://stackoverflow.com/a/6309420/957731) answer. Forms have semantic value even if the data is sent using AJAX. – ivarni Jul 15 '14 at 11:38
  • Interesting comment but in my case the page is sufficiently complex for the enter key not to mean anything. If I had to manage that key manually, I wouldn't know what to do with it. – Luke Skywalker Jul 16 '14 at 06:11
  • Ivarni, in the example you provided, the form is not connected to a controller. To access myForm.myInput.$valid, do I need to precise ng-controller="myFormController" and implement an empty controller in the javascript code or is there some default controller automatically created by Angular? – Luke Skywalker Jul 16 '14 at 06:13
  • 1
    No, Angular overrides the `form` element with a directive, so once you use `
    ` tag a FormController is created automatically. Take a look at https://docs.angularjs.org/api/ng/directive/form
    – ivarni Jul 16 '14 at 06:14
  • 1
    More specifically, "If the name attribute is specified, the form controller is published onto the current scope under this name." This is what lets you dot your way in to access the `$valid` property. – ivarni Jul 16 '14 at 06:16