開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Safari(Web browser)
- JavaScript 第6版 (David Flanagan(著)、村上 列(翻訳)、オライリージャパン)(参考書籍)
- JavaScriptリファレンス 第6版(David Flanagan(著)、木下 哲也(翻訳)、オライリージャパン)(参考書籍)
Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 5(Functions)、27(Validating Inputs)を取り組んでみる。
27(Validating Inputs)
コード(Emacs)
<label for="first0">
Enter the first name:
</label>
<input id="first0" type="text" value="J">
<br>
<label for="last0">
Enter the last name:
</label>
<input id="last0" type="text" value="">
<br>
<label for="zip0">
Enter the ZIP code:
</label>
<input id="zip0" type="text" value="ABCDE">
<br>
<label for="employee_id0">
Enter an employee ID:
</label>
<input id="employee_id0" type="text" value="A12-1234">
<br>
<div id="output0"></div>
<script src="sample27.js"></script>
(function () {
'use strict';
var input_first = document.querySelector('#first0'),
input_last = document.querySelector('#last0'),
input_zip = document.querySelector('#zip0'),
input_employee_id = document.querySelector('#employee_id0'),
inputs = [input_first, input_last, input_zip, input_employee_id],
div_output = document.querySelector('#output0'),
validateFilledIn,
validateAtLeastTwoCharacters,
validateFormat,
validateNumber,
validateInput;
validateFilledIn = function (val) {
return val !== '';
};
validateAtLeastTwoCharacters = function (val) {
return val.length >= 2;
};
validateFormat = function (val) {
return /^\w{2}-\d{1,4}$/.test(val);
};
validateNumber = function (val) {
return /^\d+$/.test(val);
};
validateInput = function () {
var first = input_first.value,
last = input_last.value,
zip = input_zip.value,
employee_id = input_employee_id.value,
output = '',
nl = '<br>';
if (!validateFilledIn(first)) {
output += 'The first name must be filled in.' + nl;
}
if (validateFilledIn(first) && !validateAtLeastTwoCharacters(first)) {
output += '"' + first +
'" is not a valid first name. It is too short.' + nl;
}
if (!validateFilledIn(last)) {
output += 'The last name must be filled in.' + nl;
}
if (validateFilledIn(last) && !validateAtLeastTwoCharacters(last)) {
output += '"' + last +
'" is not a valid last name. It is too short.' + nl;
}
if (!validateNumber(zip)) {
output += 'The ZIP must be numeric.' + nl;
}
if (!validateFormat(employee_id)) {
output += employee_id + ' is not a valid ID. ' + nl;
}
if (output === '') {
output = 'There were no errors found.';
}
div_output.innerHTML = output;
};
inputs.forEach(function (input) {
input.onchange = validateInput;
});
validateInput();
}());
0 コメント:
コメントを投稿