제이쿼리로 유효성 검사하는 수업 때 잘한 사람들 코드를 가져와서 올려보았다.
여러 방식이 있어서 참고하면 좋을 거 같다.
상진
<script>
// Js009_DOM5_practice1.html 과 같은 동작을 jQuery 로 작성해보세요.
// 아래의 HTML 은 수정하지 마세요
// 아래 HTML 안에 inline JS 코드 없이 동작할수 있도록 아래에 작성해보세요
$(document).ready(function(){
changeBOX(),
onSubmit(),
datainput()
});
function datainput(){
$("[type='text'],[type='number']").focusin(function(){
$(this).css("background-color","yellow");
}),
$("[type='text'],[type='number']").focusout(function(){
$(this).css("background-color","white");
})
}
//라디오 화면 전환
function changeBOX(){
$("[name='option']:checked").attr("disabled",true);
$("[name='option']").click(function(){
// 선택된 라디오 버튼 비활성화
$(this).attr("disabled",true),
$(this).siblings().attr("disabled",false),
// 폼 디스플레이 설정
$("form").hide(),
$('form').eq($("[name='option']:checked").index()).show("slow",function(){
$("form input").val("")
});
})
}
// 데이터 서브밋 및 검사
function onSubmit(){
$("#btn").click(function(){
switch($("[name='option']:checked").index()){
case 0:
if($("[name='name']").val().trim().length == 0){
alert("구매자명을 입력하세요"); break;}
if($("[name='price']").val().trim().length == 0){
alert("결제 금액을 입력하세요"); break;}
formSubmit(); break;
case 1:
let regexp_email = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
if(!regexp_email.test($("[name='email']").val().trim())){
alert("이메일을 입력하세요"); break;}
formSubmit(); break;
case 2:
let cardChack = false;
let regexp_number = /\d{4}/;
$("[name='cardNum']").each(function(){;
if(!regexp_number.test($(this).val().trim())){
alert("카드번호를 입력하세요!");
cardChack = true;
return false;
}
});
if(cardChack) break;
formSubmit();
}
}
)}
function formSubmit(){
$('form').eq($("[name='option']:checked").index()).submit()
}
</script>
이종현
<script>
// Js009_DOM5_practice1.html 과 같은 동작을 jQuery 로 작성해보세요.
// 아래의 HTML 은 수정하지 마세요
// 아래 HTML 안에 inline JS 코드 없이 동작할수 있도록 아래에 작성해보세요
$(document).ready(function() {
let n = 0;
const $input = $("#receiptOption input");
const $forms = $("form");
const $btn = $("#btn");
// 각 form에 대한 정규식 패턴 배열
const regexPatterns = [
[
/^[^\s]+$/,
/^[1-9]+$/
],
[
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
],
[
/^\d{4}$/
]
];
$input.click(function() {
$forms.hide();
for (let i = 0; i < 3; i++) {
if ($input[i].checked) {
$forms.eq(i).show();
n = i;
// console.log(n)
}
}
});
$btn.click(function() {
const selectedForm = $forms.eq(n);
const inputs = selectedForm.find("input");
let isValid = true;
let err = '';
inputs.each(function(i) {
const value = $(this).val();
if(n==2) i = 0;
let pattern = regexPatterns[n][i];
if (!pattern.test(value)) {
isValid = false;
err = $(this).parent().prev("th").text();
return false;
}
});
if (!isValid) {
alert(err);
return false;
}
$forms.eq(n).submit();
});
});
</script>
전광현님
<script>
// Js009_DOM5_practice1.html 과 같은 동작을 jQuery 로 작성해보세요.
// 아래의 HTML 은 수정하지 마세요
// 아래 HTML 안에 inline JS 코드 없이 동작할수 있도록 아래에 작성해보세요
$(document).ready(function(){
// $("#receiptOption input").eq(0).click(function(){
// $(".inner_table").eq(0).show();
// $(".inner_table").eq(1).hide();
// $(".inner_table").eq(2).hide();
// });
// $("#receiptOption input").eq(1).click(function(){
// $(".inner_table").eq(0).hide();
// $(".inner_table").eq(1).show();
// $(".inner_table").eq(2).hide();
// });
// $("#receiptOption input").eq(2).click(function(){
// $(".inner_table").eq(0).hide();
// $(".inner_table").eq(1).hide();
// $(".inner_table").eq(2).show();
// });
$("#receiptOption input").each(function(){
$(this).click(function(){
for(let i = 0; i < $("#receiptOption input").length; i++) {
// if($("#receiptOption input")[i].checked) {
// $(".inner_table").eq(i).show();
// $(".inner_table").eq(i).siblings("form").hide();
// }
$("#receiptOption input")[i].checked ?
$(".inner_table").eq(i).show() : $(".inner_table").eq(i).hide();
}
});
});
$("#btn").click(function(){
if($("#receiptOption input")[0].checked) {
const frm1 = $(".inner_table")[0];
let name = frm1.name.value.trim();
let price = frm1.price.value.trim();
if (name === "") {
alert("구매자명을 입력하세요")
frm1.name.focus();
return;
}
if (isNaN(price) || price === "") {
alert("결제금액을 입력하세요")
frm1.price.focus();
return;
}
confirm("제출하시겠습니까?") && frm1.submit();
return;
}
if($("#receiptOption input")[1].checked) {
const frm2 = $(".inner_table")[1];
let email = frm2.email.value.trim();
var emailRegex = /^[A-Za-z0-9_\.\-]+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;
if (!emailRegex.test(email)) {
alert("유효한 email이 아닙니다")
frm2.email.focus();
return;
}
confirm("제출하시겠습니까?") && frm2.submit();
return;
}
if($("#receiptOption input")[2].checked) {
const frm3 = $(".inner_table")[2];
var cardNumRegex = /^\d{4}/;
for(let i = 0; i < frm3.length; i++ ) {
if(!cardNumRegex.test(frm3[i].value.trim())) {
alert("유효한 카드번호가 아닙니다")
frm3.cardNum[i].focus();
return;
}
}
confirm("제출하시겠습니까?") && frm3.submit();
return;
}
});
});
</script>
이기원
<script>
// Js009_DOM5_practice1.html 과 같은 동작을 jQuery 로 작성해보세요.
// 아래의 HTML 은 수정하지 마세요
// 아래 HTML 안에 inline JS 코드 없이 동작할수 있도록 아래에 작성해보세요
// TODO
$(document).ready(function () {
$("#btn").click(function (event) {
($(".longText[name='name']").val() == "") && alert("구매자 명을 입력 하시오");
($(".longText[name='price']").val() == "") && alert("금액을 입력 하시오");
($(".longText[name='email']").val() == "") && alert("이메일을 입력 하시오");
})
$("input").click(function () {
let $inputVal = $(this).val();
$("form").hide();
($inputVal == "구매자명+금액") && $("form[name='frm1']").show();
($inputVal == "이메일") && $("form[name='frm2']").show();
($inputVal == "카드번호") && $("form[name='frm3']").show();
})
})
</script>
댓글 영역