tailieunhanh - Học JavaScript qua ví dụ part 89

Kiểm tra số điện thoại hợp lệ Một số điện thoại hợp lệ của Hoa Kỳ có mười chữ số: mã vùng của ba chữ số, tiếp theo là số thuê bao của bảy chữ số. Có thể có các dấu ngoặc đơn bao quanh các mã vùng, và dấu gạch ngang | Form Validation with Regular Expressions 777 EXPLANATION continued 3 The regular expression test method will return true if a valid Social Security number was entered and false if not. 4 If nothing was entered in the text box the user will be alerted focus will go to the text field and the form will not be submitted. 5 The onSubmit event handler will be triggered when the user clicks the submit button of line 7. 6 The input type is a text field that will hold up to 11 characters. 7 When the user clicks the submit button the onSubmit event handler will be triggered. It will call the okSocial function to validate the Social Security number. See Figure . Figure The user enters a valid Social Security number. Checking for Valid Phone Numbers A valid . phone number has ten digits an area code of three digits followed by the subscriber number of seven digits. There might be parentheses surrounding the area code and dashes or spaces separating the numbers in the subscriber number. With regular expressions you can test for any or all of these conditions and then if necessary remove the extraneous characters leaving just numbers. Example demonstrates how to validate a simple . phone number. EXAMPLE html head title Validating Phone Numbers title script type text javascript function ok_Phone phform 1 var regex A d 3 - s d 3 s - d 4 2 if return true Continues From the Library of 778 Chapter 17 Regular Expressions and Pattern Matching EXAMPLE continued 3 4 5 else alert Enter a valid phone number return false script head body hr h2 Checking for a Valid Phone Number h2 form name formtest action http localhost cgi-bin method post onSubmit return ok_Phone this p Please input p input input form body html enter your phone br type text size 40 name user_phone type submit value Submit type reset value Clear EXPLANATION 1 The regular expression reads Start at the beginning of the .

TỪ KHÓA LIÊN QUAN