[プログラム] 日本電話番号の入力チェック PHP&JavaScript


2025-10-10 07:58
18
0
본문
■サーバー側
// 入力情報の電話番号を取得
$tel = trim($_post['tel'] ?? '');
// 電話番号の形式チェック(例: 03-1234-5678 / 090-1234-5678 など)
if (!preg_match('/^0\d{1,4}-\d{1,4}-\d{3,4}$/', $tel)) {
$errors['tel'] = '電話番号の形式が正しくありません。(例:03-1234-5678)';
}
★ポイント
/^0\d{1,4}-\d{1,4}-\d{3,4}$/
・先頭は必ず「0」
・ハイフン区切りを必須
・各区切りの桁数は柔軟(携帯・固定電話対応)
★許可される例
03-1234-5678
045-123-4567
090-1234-5678
0990-12-3456
★不正な例
3-1234-5678
123-456-7890
0312345678(ハイフンなし)
03--1234-5678(二重ハイフン)
■クライアント側
document.getElementById('tel').addEventListener('blur', function() {
const tel = this.value.trim();
const telError = document.getElementById('telError');
const pattern = /^0\d{1,4}-\d{1,4}-\d{3,4}$/;
if (tel && !pattern.test(tel)) {
telError.textContent = '電話番号の形式が正しくありません。(例:03-1234-5678)';
} else {
telError.textContent = '';
}
});
// 入力情報の電話番号を取得
$tel = trim($_post['tel'] ?? '');
// 電話番号の形式チェック(例: 03-1234-5678 / 090-1234-5678 など)
if (!preg_match('/^0\d{1,4}-\d{1,4}-\d{3,4}$/', $tel)) {
$errors['tel'] = '電話番号の形式が正しくありません。(例:03-1234-5678)';
}
★ポイント
/^0\d{1,4}-\d{1,4}-\d{3,4}$/
・先頭は必ず「0」
・ハイフン区切りを必須
・各区切りの桁数は柔軟(携帯・固定電話対応)
★許可される例
03-1234-5678
045-123-4567
090-1234-5678
0990-12-3456
★不正な例
3-1234-5678
123-456-7890
0312345678(ハイフンなし)
03--1234-5678(二重ハイフン)
■クライアント側
document.getElementById('tel').addEventListener('blur', function() {
const tel = this.value.trim();
const telError = document.getElementById('telError');
const pattern = /^0\d{1,4}-\d{1,4}-\d{3,4}$/;
if (tel && !pattern.test(tel)) {
telError.textContent = '電話番号の形式が正しくありません。(例:03-1234-5678)';
} else {
telError.textContent = '';
}
});
댓글목록0