forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular.validator.html
70 lines (61 loc) · 2.55 KB
/
angular.validator.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<h1>angular.validator</h1>
<h2>Overview</h2>
<p>Validators are a standard way to check the user input against a specific criteria. For
example, you might need to check that an input field contains a well-formed phone number.</p>
<h2>Syntax</h2>
<p>Attach a validator on user input widgets using the <code>ng:validate</code> attribute.</p>
<p><doc:example>
<doc:source>
Change me: <input type="text" name="number" ng:validate="integer" value="123">
</doc:source>
<doc:scenario>
it('should validate the default number string', function() {
expect(element('input[name=number]').attr('class')).
not().toMatch(/ng-validation-error/);
});
it('should not validate "foo"', function() {
input('number').enter('foo');
expect(element('input[name=number]').attr('class')).
toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example></p>
<h2>Writing your own Validators</h2>
<p>Writing your own validator is easy. To make a function available as a
validator, just define the JavaScript function on the <code>angular.validator</code>
object. <tt><angular/></tt> passes in the input to validate as the first argument
to your function. Any additional validator arguments are passed in as
additional arguments to your function.</p>
<p>You can use these variables in the function:</p>
<ul>
<li><code>this</code> — The current scope.</li>
<li><code>this.$element</code> — The DOM element containing the binding. This allows the filter to manipulate
the DOM in addition to transforming the input.</li>
</ul>
<p>In this example we have written a upsTrackingNo validator.
It marks the input text "valid" only when the user enters a well-formed
UPS tracking number.</p>
<h2>Example</h2>
<doc:example>
<doc:source>
<script>
angular.validator('upsTrackingNo', function(input, format) {
var regexp = new RegExp("^" + format.replace(/9/g, '\\d') + "$");
return input.match(regexp)?"":"The format must match " + format;
});
</script>
<input type="text" name="trackNo" size="40"
ng:validate="upsTrackingNo:'1Z 999 999 99 9999 999 9'"
value="1Z 123 456 78 9012 345 6"/>
</doc:source>
<doc:scenario>it('should validate correct UPS tracking number', function() {
expect(element('input[name=trackNo]').attr('class')).
not().toMatch(/ng-validation-error/);
});
it('should not validate in correct UPS tracking number', function() {
input('trackNo').enter('foo');
expect(element('input[name=trackNo]').attr('class')).
toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>