Javascript - Kiểm tra tính hợp lệ của dữ liệu theo mẫu địa chỉ thanh toán chuẩn Canadian và American. | How to Use JavaScript to Validate Form Data?


Lang thang kiếm mấy bài viết trên mạng đọc chơi thấy có mẫu địa chỉ thanh toán chuẩn dùng cho 2 nước Canadian và American. Mẫu này có hỗ trợ kiểm tra dữ liệu nhập theo tiêu chuẩn của Canadian và American, và nó cũng hỗ trợ loại bỏ các khoảng trắng dư thừa trong dữ liệu nhập.

Thấy cũng hay hay nên viết lại để sau này có dịp cần dùng thì cũng có thể lấy ra tham khảo. Do mục đích chỉ dùng để tham khảo sau này nên mình không phân tích code mà chỉ sao chép y chang thôi ^^!


Live Demo:



HTML Source:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
    <meta name="WT.qs_dlk" content="UgUJDgrIZ24AAHkAvU4AAAAY">
    <meta name="WT.qs_shmv" content="hv20130110-astbury.sf.quinstreet.net">
    <meta name="inject_params" content="WT.qs_dlk=UgUJDgrIZ24AAHkAvU4AAAAY&amp;">
    <meta http-equiv="Set-Cookie" content="inject_params=WT.qs_dlk=UgUJDgrIZ24AAHkAvU4AAAAY&amp;; path=/;  domain=webreference.com;">
    <meta http-equiv="Set-Cookie" content="WMUUID=UgUJDgrIZ24AAHkAvU4AAAAY; path=/;  domain=webreference.com;">
<title>Example Form</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" type="text/css" href="Example%20Form_files/newStyle.css">
<!-- JavaScript Form Validation by Joseph K. Myers -->
<script type="text/javascript" src="Example%20Form_files/val.js"></script>
<script type="text/javascript">
<!--
function highLabel(e, value) {
e = document.getElementById('l'+e.name);
if (e)
e.style.background = value;
}
function initForm(f) {
var e, i;
for (i=0; i<f.elements.length; i++) {
e = f.elements[i];
/* ignore fields with multiple elements */
if (e.type == 'text' && !e.length) {
e.onfocus = function() {
highLabel(this, '#ccf');
};
e.onblur = function() {
highLabel(this, '');
};
}
}
}
setTimeout('initForm(document.forms["az1"])', 1000);
errc[31] = 'Please enter your two-letter state abbreviation.';
billing_address_check = {
name:{ verify: text, filter: true, message: 'Please enter your first name.' },
surname: { filter: 1,
verify: text, message: 'Please enter your last name.', filter:1 },
address: { filter: 1,
verify: words, message: 'Please enter your address.' },
city: { filter: 1, verify: text, message: 'Please enter your city.' },
state: { filter: 1, verify: function(s) {
 var a = nwts(s).toUpperCase().match(/^[a-z]{2}$/ig);
 err = a != null && a.length ? 0 : 31;
 return a;
} },
zip: { verify: zip, filter: 1, force: 1 },
phone: { verify: tel, filter: 1, force:1 },
email: { verify: email, filter: 1, force: 1 }
};
</script>
</head>
<!-- comment -->
<body>
<h1>Example Form</h1>
<form name="az1" onsubmit="return validate(this, billing_address_check)">
<fieldset>
<legend><b>Fill in your billing address.</b></legend>
<dl>
<dt><label id="lname" for="n1">First name</label> and <label id="lsurname" for="n2">Last name</label></dt>
<dd><input name="name" id="n1" type="text">
<input name="surname" id="n2" type="text"></dd>
<dt><label id="laddress" for="address">Address</label></dt>
<dd><input name="address" size="40" onfocus="highLabel('a1', '#ccf')" onblur="highLabel('a1', '')" type="text"></dd>
<dt><label id="lcity">City</label>, <label id="lstate">State (two-letter abbreviation)</label>, and <label id="lzip">Zip</label></dt>
<dd><input name="city" type="text">,
<input name="state" size="4" maxlength="2" type="text">
<input name="zip" size="12" maxlength="10" type="text"></dd>
<dt><label id="lphone">Phone (area code and number)</label> and <label id="lemail">Email</label></dt>
<dd><input name="phone" size="18" type="text">
<input name="email" size="35" type="text"></dd>
</dl>
<p><input onclick="validate(this.form, billing_address_check)&amp;&amp; alert('All required fields are OK!')" value="Validate the Billing Address" type="button"></p>
</fieldset>
</form>
</body></html>


Source val.js file:

err = 0;
errc = ['OK'];
errc[1] = 'Please verify the zip code (5 or 9 digits).';
errc[2] = 'Please enter the telephone number, including area code.';
errc[3] = 'Please check the expiration date: four digits, '
+ 'e.g., 0709 is the correct date for July, 2009.';
errc[4] = 'This card is not working; can you check the card number again?';
errc[5] = 'Please do not leave this field blank.';
errc[6] = 'Please fill in the email address.';
errc[7] = 'Please check the expiration date: apparently it is expired.';
errc[8] = 'Please check the expiration date: it is not valid.';
errc[9] = 'Please complete the entry.';
errc[10] = 'Please enter a numerical value (may include an exponent e+N).';
errc[11] = 'Please enter a complete URL.';

function nwts(s) { // no white space
return s.replace(/\s+/g, '');
}
function trimwts(s) { // trim white space
return s.replace(/^\s+|\s+$/g, '');
}

function number(s) { // any number, including exponent
s = nwts(s)-0;
err = isNaN(s) ? 10 : 0;
return [err ? 0 : s];
}

function zip(s) { // zip code
var a = nwts(s).match(/\d{5}(-?\d{4}){0,1}/g);
err = a != null && a.length ? 0 : 1;
return a;
}

function tel(s) { // telephone, with area code + opt prefixes
var a = s.replace(/\D+/g, '-');
a = a.match(/(\d+-?)*(\d{3}-?){2}\d{4}/g);
err = a != null && a.length ? 0 : 2;
return a;
}

/* this code is copied from
http://www.codelib.net/home/jkm/checksum.js */
function checksum(s) { // thanks to daniel_amor@hp.com for AMEX specs
var p=0, e=8, t=0, c=[], r=0, l=0, i;
if (s.length != 16) {
t = 1;
e = s.length == 13 && 6 || s.length == 15 && 7;
}
for (i=p; i<e; i++)
r += (c[i] = s.charAt(i*2+t) * 2) > 9
? Math.floor(c[i]/10 + c[i]%10)
: c[i];
for (i=p; i<e+t; i++) l += s.charAt(i*2+1-t)-0;
l += r;
return e && l%10 == 0;
}

function cardno(s) {
s = s.replace(/\D+/g, '');
err = checksum(s) ? 0 : 4;
return [s];
}

function text(s) {
s = trimwts(s);
err = s.length ? 0 : 5;
return [s];
}

function words(s) {
s = trimwts(s);
err = /\s/.test(s) ? 0 : 9;
return [s];
}

function email(s) {
a = s.match(/\S+@([-\w]+\.)+\w+/g);
err = a != null && a.length ? 0 : 6;
return a;
}

function url(s) {
a = s.match(/\w{2,}:\/{2}([-\w]+\.)+\w+\S*/g);
err = a != null && a.length ? 0 : 11;
return a;
}

function expires(s) {
s = nwts(s);
var m = new Date()
var m_year = m.getFullYear()%100, m_month = m.getMonth();
if (s.length != 4 || isNaN(s))
err = 3;
else {
s_month = s.substring(0,2)-0;
s_year = s.substring(2, 4)-0;
if (m_year > 70 && s_year < 30) s_year += 100;
/* "Let your great grandson worry about that." */
if (s_year < m_year || s_year > m_year + 7) err = 8;
else if (s_year == m_year && !(s_month > m_month)) err = 7;
else err = 0;
}
return [s];
}

function valid(element, check) {
if (element.type == 'text' || element.type == 'textarea') {
return check(element.value);
} else return check(element);
}

present_element = null, present_error = null;
function validate(form, list) {
for (i=0; i<form.elements.length; i++) {
var element = form.elements[i];
var n = element.name, out;
if (list[n] && list[n].verify) {
out = valid(element, list[n].verify);
if (err && (list[n].force || list[n].err != err)) {
list[n].err = err;
present_error = err;
present_element = element;
alert(list[n].message || errc[err]);
element.focus();
return false;
} else if (!err && list[n].filter)
element.value = out.join(', ');
}
}
return true;
}


Tải về - Download:





Source: webreference







No comments:

Post a Comment