One of Angular's strength's is client-side form validation.
Dealing with traditional form inputs and having to use interrogative jQuery-style processing can be time-consuming and finicky. Angular allows you to produce professional interactive forms relatively easily.
The ng-model directive provides two-way binding with input fields and usually the novalidate attribute is also placed on the form element to prevent the browser from doing native validation.
Thus, a simple form would look like:
<form name="form" novalidate> <label name="email"> Your email </label> <input type="email" name="email" ng-model="email" /> </form>
For Angular to validate inputs, use exactly the same syntax as a regular input element, except for the addition of the ng-model attribute to specify which variable to bind to on the scope. Email is shown in the prior example. To validate a number, the syntax would be:
<input type="number" name="postalcode" ng-model="zipcode" />
The final steps to basic form validation are connecting to a form submit function on the controller using ng-submit, rather than allowing the default form submit to occur. This is not mandatory but it is usually used, as the input variables are already available on the scope and so available to your submit function. It is also usually good practice to give the form a name. These changes would result in the following syntax:
<form name="signup_form" ng-submit="submitFunc()" novalidate> <label name="email"> Your email </label> <input type="email" name="email" ng-model="email" /> <button type="submit">Signup</button> </form>
This above code is functional but there is other functionality that Angular provides.
The next step is to understand that Angular attaches class attributes using ng-pristine, ng-dirty, ng-valid and ng-invalid for form processing. Using these classes in your css will allow you to style valid/invalid and pristine/dirty input fields and so alter the presentation as the user is entering data into the form.