【JS】フォームバリデーション
by tea4two
HTML
<form action="" method="post" name="theForm">
<p id="error"></p>url
<br>
<input type="text" name="myurl" id="myurl">
<br>
<br>選択:
<br>
<select name="select" id="select">
<option value=""></option>
<option value="http://thissite.com/">this site</option>
<option value="http://thatsite.com/">that site</option>
<option value="http://anohtersite.com/">another site</option>
</select>
<br>
<br>TEL:
<br>
<input type="text" id="tel" name="tel">
<br>
<br>TEL(matchを使ったバージョン):
<br>
<br>
<input type="text" id="tel2" name="tel2">
<br>
<br>TEL(placeholder)
<br>
<input type="text" id="tel3" name="tel3" pattern="\d{3}\-\d{3}\-\d{4}" placeholder="123-456-7890">
<br>
<br>
</form>
CSS
#error {
color: red;
}
JavaScript
/* URL */
document.theForm.myurl.onblur = function () {
theURL = document.theForm.myurl.value;
if (theURL === '') {
document.getElementById('error').innerHTML = 'URLはブランクにしないでね。';
}
if (theURL === 'http://') {
document.getElementById('error').innerHTML = 'URLをちゃんと入れてください。';
}
}
document.theForm.myurl.onchange = function () {
theURL = document.theForm.myurl.value;
console.log(theURL.indexOf('http://'));
if (theURL.indexOf('http://')) {
//if not find return -1
document.getElementById('error').innerHTML = "URLは「http://」で始めてください。";
} else {
//if found and is begins with http:// return 0
document.getElementById('error').innerHTML = '';
}
}
/* select */
document.theForm.select.onchange = function () {
var id = document.theForm.select.selectedIndex;
console.log(id);
var url = document.theForm.select[id].value;
//jump to url
window.location.href = url;
}
/* TEL */
var telField = document.getElementById('tel');
var telError = document.getElementById('error');
telField.onchange = function () {
// \d{3}[\-]\d{3}[\-]\d{4} cannot be accepted to seach()
//needed to be turned into string
//\\d{3}[\\-]\\d{3}[\\-]\\d{4}
var telPattern = new RegExp('\\d{3}[\\-]\\d{3}[\\-]\\d{4}', 'i'); //i is case-insensitive
//条件式ごと変数へ代入
var isValid = (this.value.search(telPattern) >= 0); //if not found returns -1
console.log(isValid);
//check it out now!
if (!isValid) {
//not valid
telError.innerHTML = '形式がちがうよ。124-456-7890で';
} else {
//valid
telError.innerHTML = '';
}
} //telField
/* TEL2 */
var tel2field = document.getElementById('tel2');
tel2field.onchange = function () {
var pat = /\d{3}\-\d{3}\-\d{4}/i, //正規表現は文字列にしない
patArr = this.value.match(pat); //返り値は配列にストックされる
console.log(this.value);
console.log(patArr);
if (!patArr) {
//not valid
telError.innerHTML =...