Slide14 - RegularExpressions - and - JS Form
Slide14 - RegularExpressions - and - JS Form
Session 12
(slot 22-23)
Objectives
◼ Describe regular expression
◼ Validate data in form
Regular Expressions
▪ A regular expression is a pattern, whose purpose is to help in
validating the text format
▪ Example:
Creating a regular expression
// → true
console.log(/[0-9]/.test("in 1992"));
// → true
Types
Character or symbols allow matching a substring that exists at
a specific position within a string.
Types
Characters or symbols are combined to form character classes for
specifying patterns.
Repeating parts of a pattern
◼ We now know how to match a single digit. What if we want to match a
whole number—a sequence of one or more digits?
◼ When you put a plus sign (+) after something in a regular expression, it
indicates that the element may be repeated more than once. Thus,
/\d+/ matches one or more digit characters.
◼ The star (*) has a similar meaning but also allows the pattern to match
zero times.
◼ A question (?) mark makes a part of a pattern optional, meaning it may
occur zero times or one time.
Repeating parts of a pattern
console.log(/'\d+'/.test("'123'"));
// → true
console.log(/'\d+'/.test("''"));
// → false
console.log(/'\d*'/.test("'123'"));
// → true
console.log(/'\d*'/.test("''"));
// → true
Repeating parts of a pattern
let neighbor = /neighbou?r/;
console.log(neighbor.test("neighbour"));
// → true
console.log(neighbor.test("neighbor"));
// → true
Repeating parts of a pattern
◼ To indicate that a pattern should occur a precise number of
times, use braces.
◼ Putting {4} after an element, for example, requires it to occur
exactly four times.
◼ It is also possible to specify a range this way: {2,4} means
the element must occur at least twice and at most four times.
◼ You can also specify open-ended ranges when using braces by
omitting the number after the comma. So, {5,} means five or
more times.
Repeating parts of a pattern
console.log(dateTime.test("1-30-2003 8:45"));
// → true
Properties and Methods
Validate data in form
❑Data validation is the process of ensuring that computer input is clean, correct,
and useful.
❑Typical validation tasks are:
✓has the user filled in all required fields?
✓has the user entered a valid date?
✓has the user entered text in a numeric field?
❑ Data validation is to ensure correct input to a computer application.
❑ Deployed in many different ways.
✓Server side validation is performed by a web server, after input has been
sent to the server.
✓Client side validation is performed by a web browser, before input is sent to
a web server.
Example: check form field is empty