diff --git a/docs/content/guide/forms.ngdoc b/docs/content/guide/forms.ngdoc index 35299f35e401..636163cc2e97 100644 --- a/docs/content/guide/forms.ngdoc +++ b/docs/content/guide/forms.ngdoc @@ -7,15 +7,17 @@ Controls (`input`, `select`, `textarea`) are ways for a user to enter data. A Form is a collection of controls for the purpose of grouping related controls together. Form and controls provide validation services, so that the user can be notified of invalid input. -This provides a better user experience, because the user gets instant feedback on how to correct the error. -Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus can not be trusted. +This provides a better user experience, because the user gets instant feedback on how to +correct the error. Keep in mind that while client-side validation plays an important role +in providing good user experience, it can easily be circumvented and thus can not be trusted. Server-side validation is still necessary for a secure application. # Simple form The key directive in understanding two-way data-binding is {@link ng.directive:ngModel ngModel}. -The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. -In addition it provides an {@link ngModel.NgModelController API} for other directives to augment its behavior. +The `ngModel` directive provides the two-way data-binding by synchronizing the model to the view, +as well as view to the model. In addition it provides an {@link ngModel.NgModelController API} +for other directives to augment its behavior. @@ -60,16 +62,20 @@ Note that `novalidate` is used to disable browser's native form validation. To allow styling of form as well as controls, `ngModel` adds these CSS classes: -- `ng-valid` -- `ng-invalid` -- `ng-pristine` -- `ng-dirty` -- `ng-touched` -- `ng-untouched` +- `ng-valid`: the model is valid +- `ng-invalid`: the model is invalid +- `ng-valid-[key]`: for each valid key added by `$setValidity` +- `ng-invalid-[key]`: for each invalid key added by `$setValidity` +- `ng-pristine`: the control hasn't been interacted with yet +- `ng-dirty`: the control has been interacted with +- `ng-touched`: the control has been blurred +- `ng-untouched`: the control hasn't been blurred +- `ng-pending`: any `$asyncValidators` are unfulfilled The following example uses the CSS to display validity of each form control. -In the example both `user.name` and `user.email` are required, but are rendered with red background only when they are dirty. -This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity. +In the example both `user.name` and `user.email` are required, but are rendered +with red background only when they are dirty. This ensures that the user is not distracted +with an error until after interacting with the control, and failing to satisfy its validity. @@ -122,9 +128,9 @@ A form is an instance of {@link form.FormController FormController}. The form instance can optionally be published into the scope using the `name` attribute. Similarly, an input control that has the {@link ng.directive:ngModel ngModel} directive holds an -instance of {@link ngModel.NgModelController NgModelController}. -Such a control instance can be published as a property of the form instance using the `name` attribute -on the input control. The name attribute specifies the name of the property on the form instance. +instance of {@link ngModel.NgModelController NgModelController}.Such a control instance +can be published as a property of the form instance using the `name` attribute on the input control. +The name attribute specifies the name of the property on the form instance. This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives. @@ -187,7 +193,7 @@ This allows us to extend the above example with these features: -# Custom triggers +# Custom model update triggers By default, any change to the content will trigger a model update and form validation. You can override this behavior using the {@link ng.directive:ngModelOptions ngModelOptions} directive to @@ -200,8 +206,8 @@ and validation, add "default" as one of the specified events. I.e. `ng-model-options="{ updateOn: 'default blur' }"` -The following example shows how to override immediate updates. Changes on the inputs within the form will update the model -only when the control loses focus (blur event). +The following example shows how to override immediate updates. Changes on the inputs within the form +will update the model only when the control loses focus (blur event). @@ -241,10 +247,11 @@ in `debounce`. This can be useful to force immediate updates on some specific ci I.e. `ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"` -If those attributes are added to an element, they will be applied to all the child elements and controls that inherit from it unless they are -overridden. +If those attributes are added to an element, they will be applied to all the child elements and +controls that inherit from it unless they are overridden. -This example shows how to debounce model changes. Model will be updated only 250 milliseconds after last change. +This example shows how to debounce model changes. Model will be updated only 250 milliseconds +after last change. @@ -264,39 +271,40 @@ This example shows how to debounce model changes. Model will be updated only 250 - - # Custom Validation Angular provides basic implementation for most common HTML5 {@link ng.directive:input input} -types: ({@link input[text] text}, {@link input[number] number}, {@link input[url] url}, {@link input[email] email}, {@link input[radio] radio}, {@link input[checkbox] checkbox}), as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, `min`, `max`). - -You can define your own validator by defining a directive which adds a validation function to the `ngModel` {@link ngModel.NgModelController controller}. -The directive can get ahold of `ngModel` by specifying `require: 'ngModel'` in the directive definition. -See below for an example. - -Validation runs in two places: - - * **Model to View update** - - The functions in {@link ngModel.NgModelController#$formatters `NgModelController.$formatters`} are pipelined. - Whenever the bound model changes, each of these functions has an opportunity to format the value and change validity state of the form control through {@link ngModel.NgModelController#$setValidity `NgModelController.$setValidity`}. - - * **View to Model update** - - In a similar way, whenever a user interacts with a control it calls {@link ngModel.NgModelController#$setViewValue `NgModelController.$setViewValue`}. - -This in turn runs all functions in the {@link ngModel.NgModelController#$parsers `NgModelController.$parsers`} array as a pipeline. Each function in `$parsers` has an opportunity to convert the value and change validity state of the form control through {@link ngModel.NgModelController#$setValidity `NgModelController.$setValidity`}. - -In the following example we create two directives. - - * The first one is `integer` and it validates whether the input is a valid integer. - For example `1.23` is an invalid value, since it contains a fraction. - Note that we unshift the array instead of pushing. - This is because we want it to be the first parser and consume the control string value, as we need to execute the validation function before a conversion to number occurs. - - * The second directive is a `smart-float`. - It parses both `1.2` and `1,2` into a valid float number `1.2`. - Note that we can't use input type `number` here as HTML5 browsers would not allow the user to type what it would consider an invalid number such as `1,2`. - +types: ({@link input[text] text}, {@link input[number] number}, {@link input[url] url}, +{@link input[email] email}, {@link input[radio] radio}, {@link input[checkbox] checkbox}), +as well as some directives for validation (`required`, `pattern`, `minlength`, `maxlength`, +`min`, `max`). + +With a custom directive, you can add your own validation functions to the `$validators` object on +the {@link ngModel.NgModelController `ngModelController`}. To get a hold of the controller, +you require it in the directive as shown in the example below. + +Each function in the `$validators` object receives the `modelValue` and the `viewValue` +as parameters. Angular will then call `$setValidity` internally with the function's return value +(`true`: valid, `false`: invalid). The validation functions are executed every time an input +is changed (`$setViewValue` is called) or whenever the bound `model` changes. +Validation happens after successfully running `$parsers` and `$formatters`, respectively. +Failed validators are stored by key in +{@link ngModel.NgModelController#$error `ngModelController.$error`}. + +Additionally, there is the `$asyncValidators` object which handles asynchronous validation, +such as making an `$http` request to the backend. Functions added to the object must return +a promise that must be `resolved` when valid or `rejected` when invalid. +In-progress async validations are stored by key in +{@link ngModel.NgModelController#$pending `ngModelController.$pending`}. + +In the following example we create two directives: + * An `integer` directive that validates whether the input is a valid integer. For example, + `1.23` is an invalid value, since it contains a fraction. Note that we validate the viewValue + (the string value of the control), and not the modelValue. This is because input[number] converts + the viewValue to a number when running the `$parsers`. + + * A `username` directive that asynchronously checks if a user-entered value is already taken. + We mock the server request with a `$q` deferred. @@ -305,18 +313,18 @@ In the following example we create two directives. Size (integer 0 - 10): {{size}}
- This is not valid integer! + The value is not a valid integer! The value must be in range 0 to 10!
- Length (float): - - {{length}}
- - This is not a valid float number! + Username: + {{name}}
+ Checking if this name is available ... + This username is already taken!
+
@@ -328,35 +336,96 @@ In the following example we create two directives. return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { - ctrl.$parsers.unshift(function(viewValue) { + ctrl.$validators.integer = function(modelValue, viewValue) { + if (ctrl.$isEmpty(modelValue)) { + // consider empty models to be valid + return true; + } + if (INTEGER_REGEXP.test(viewValue)) { // it is valid - ctrl.$setValidity('integer', true); - return viewValue; - } else { - // it is invalid, return undefined (no model update) - ctrl.$setValidity('integer', false); - return undefined; + return true; } - }); + + // it is invalid + return false; + }; } }; }); - var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/; - app.directive('smartFloat', function() { + app.directive('username', function($q, $timeout) { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { - ctrl.$parsers.unshift(function(viewValue) { - if (FLOAT_REGEXP.test(viewValue)) { - ctrl.$setValidity('float', true); - return parseFloat(viewValue.replace(',', '.')); - } else { - ctrl.$setValidity('float', false); - return undefined; + var usernames = ['Jim', 'John', 'Jill', 'Jackie']; + + ctrl.$asyncValidators.username = function(modelValue, viewValue) { + + if (ctrl.$isEmpty(modelValue)) { + // consider empty model valid + return $q.when(); } - }); + + var def = $q.defer(); + + $timeout(function() { + // Mock a delayed response + if (usernames.indexOf(modelValue) === -1) { + // The username is available + def.resolve(); + } else { + def.reject(); + } + + }, 2000); + + return def.promise; + }; + } + }; + }); +
+
+ +# Modifying built-in validators + +Since Angular itself uses `$validators`, you can easily replace or remove built-in validators, +should you find it necessary. The following example shows you how to overwrite the email validator +in `input[email]` from a custom directive so that it requires a specific top-level domain, +`example.com` to be present. +Note that you can alternatively use `ng-pattern` to further restrict the validation. + + + +
+
+ Overwritten Email: + + This email format is invalid!
+ Model: {{myEmail}} +
+
+
+ + + var app = angular.module('form-example-modify-validators', []); + + app.directive('overwriteEmail', function() { + var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i; + + return { + require: 'ngModel', + restrict: '', + link: function(scope, elm, attrs, ctrl) { + // only apply the validator if ngModel is present and Angular has added the email validator + if (ctrl && ctrl.$validators.email) { + + // this will overwrite the default Angular email validator + ctrl.$validators.email = function(modelValue) { + return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue); + }; + } } }; }); @@ -365,13 +434,17 @@ In the following example we create two directives. # Implementing custom form controls (using `ngModel`) -Angular implements all of the basic HTML form controls ({@link ng.directive:input input}, {@link ng.directive:select select}, {@link ng.directive:textarea textarea}), which should be sufficient for most cases. -However, if you need more flexibility, you can write your own form control as a directive. +Angular implements all of the basic HTML form controls ({@link ng.directive:input input}, +{@link ng.directive:select select}, {@link ng.directive:textarea textarea}), +which should be sufficient for most cases. However, if you need more flexibility, +you can write your own form control as a directive. In order for custom control to work with `ngModel` and to achieve two-way data-binding it needs to: - - implement `$render` method, which is responsible for rendering the data after it passed the {@link ngModel.NgModelController#$formatters `NgModelController.$formatters`}, - - call `$setViewValue` method, whenever the user interacts with the control and model needs to be updated. This is usually done inside a DOM Event listener. + - implement `$render` method, which is responsible for rendering the data after it passed the + {@link ngModel.NgModelController#$formatters `NgModelController.$formatters`}, + - call `$setViewValue` method, whenever the user interacts with the control and model + needs to be updated. This is usually done inside a DOM Event listener. See {@link guide/directive `$compileProvider.directive`} for more info. diff --git a/src/ng/directive/input.js b/src/ng/directive/input.js index 89bc350629c2..c50a8d872e6b 100644 --- a/src/ng/directive/input.js +++ b/src/ng/directive/input.js @@ -31,7 +31,6 @@ var inputType = { * @description * Standard HTML text input with angular data binding, inherited by most of the `input` elements. * - * *NOTE* Not every feature offered is available for all input types. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. @@ -115,7 +114,10 @@ var inputType = { * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many * modern browsers do not yet support this input type, it is important to provide cues to users on the - * expected input format via a placeholder or label. The model must always be a Date object. + * expected input format via a placeholder or label. + * + * The model must always be a Date object, otherwise Angular will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. @@ -203,7 +205,10 @@ var inputType = { * @description * Input with datetime validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. The model must be a Date object. + * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. + * + * The model must always be a Date object, otherwise Angular will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. @@ -294,6 +299,9 @@ var inputType = { * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. * + * The model must always be a Date object, otherwise Angular will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * @@ -380,7 +388,10 @@ var inputType = { * @description * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object. + * week format (yyyy-W##), for example: `2013-W02`. + * + * The model must always be a Date object, otherwise Angular will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. @@ -466,8 +477,12 @@ var inputType = { * @description * Input with month validation and transformation. In browsers that do not yet support * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is - * not set to the first of the month, the first of that model's month is assumed. + * month format (yyyy-MM), for example: `2009-01`. + * + * The model must always be a Date object, otherwise Angular will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * If the model is not set to the first of the month, the next view to model update will set it + * to the first of the month. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. @@ -556,6 +571,8 @@ var inputType = { * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * + * The model must always be a number, otherwise Angular will throw an error. + * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. @@ -634,6 +651,12 @@ var inputType = { * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * + *
+ * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex + * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify + * the built-in validators (see the {@link guide/forms Forms guide}) + *
+ * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. @@ -711,6 +734,12 @@ var inputType = { * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * + *
+ * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex + * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can + * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) + *
+ * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. @@ -1351,10 +1380,14 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt * @restrict E * * @description - * HTML input element control with angular data-binding. Input control follows HTML5 input types - * and polyfills the HTML5 validation behavior for older browsers. + * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding, + * input state control, and validation. + * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers. * - * *NOTE* Not every feature offered is available for all input types. + *
+ * **Note:** Not every feature offered is available for all input types. + * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`. + *
* * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. @@ -1490,19 +1523,20 @@ var VALID_CLASS = 'ng-valid', * @name ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. - * @property {*} $modelValue The value in the model, that the control is bound to. + * @property {*} $modelValue The value in the model that the control is bound to. * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever - the control reads value from the DOM. Each function is called, in turn, passing the value - through to the next. The last return value is used to populate the model. - Used to sanitize / convert the value as well as validation. For validation, - the parsers should update the validity state using - {@link ngModel.NgModelController#$setValidity $setValidity()}, - and return `undefined` for invalid values. + the control reads value from the DOM. The functions are called in array order, each passing the value + through to the next. The last return value is forwarded to the $validators collection. + Used to sanitize / convert the value. + Returning undefined from a parser means a parse error occurred. No $validators will + run and the 'ngModel' will not be updated until the parse error is resolved. The parse error is stored + in 'ngModel.$error.parse'. * * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever - the model value changes. Each function is called, in turn, passing the value through to the - next. Used to format / convert values for display in the control and validation. + the model value changes. The functions are called in reverse array order, each passing the value through to the + next. The last return value is used as the actual DOM value. + Used to format / convert values for display in the control. * ```js * function formatter(value) { * if (value) { @@ -1533,8 +1567,9 @@ var VALID_CLASS = 'ng-valid', * is expected to return a promise when it is run during the model validation process. Once the promise * is delivered then the validation status will be set to true when fulfilled and false when rejected. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model - * value will only be updated once all validators have been fulfilled. Also, keep in mind that all - * asynchronous validators will only run once all synchronous validators have passed. + * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator + * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators + * will only run once all synchronous validators have passed. * * Please note that if $http is used then it is important that the server returns a success HTTP response code * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. @@ -1777,19 +1812,22 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * @name ngModel.NgModelController#$setValidity * * @description - * Change the validity state, and notifies the form. + * Change the validity state, and notify the form. * - * This method can be called within $parsers/$formatters. However, if possible, please use the - * `ngModel.$validators` pipeline which is designed to call this method automatically. + * This method can be called within $parsers/$formatters or a custom validation implementation. + * However, in most cases it should be sufficient to use the `ngModel.$validators` and + * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. * - * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]` and `$pending[validationErrorKey]` - * so that it is available for data-binding. + * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned + * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` + * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), - * or skipped (null). + * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. + * Skipped is used by Angular when validators do not run because of parse errors and + * when `$asyncValidators` do not run because any of the `$validators` failed. */ addSetValidityMethod({ ctrl: this, @@ -2279,10 +2317,15 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * The following CSS classes are added and removed on the associated input/select/textarea element * depending on the validity of the model. * - * - `ng-valid` is set if the model is valid. - * - `ng-invalid` is set if the model is invalid. - * - `ng-pristine` is set if the model is pristine. - * - `ng-dirty` is set if the model is dirty. + * - `ng-valid`: the model is valid + * - `ng-invalid`: the model is invalid + * - `ng-valid-[key]`: for each valid key added by `$setValidity` + * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` + * - `ng-pristine`: the control hasn't been interacted with yet + * - `ng-dirty`: the control has been interacted with + * - `ng-touched`: the control has been blurred + * - `ng-untouched`: the control hasn't been blurred + * - `ng-pending`: any `$asyncValidators` are unfulfilled * * Keep in mind that ngAnimate can detect each of these classes when added and removed. *