这是我的多步骤注册表的一部分,并且运行良好。 但我想为“student_name”变量添加一个数字验证,这样系统就会阻止学生在名字中输入数字。
if (step === 2) {
// Example: check if username is not empty
var student_name = document.querySelector('#student_name').value;
if (student_name === '') {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Field still empty'
});
} else if (student_name.length < 3 || student_name.length > 30) {
isValid = false;
Swal.fire({
icon: 'info',
title: 'the character must <3 or >30'
});
} else
var student_email = document.querySelector('#student_email').value;
if (student_email === '') {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Field still empty'
});
} else if (!student_email.includes('@')) {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Email must include "@"'
});
}
}
所以我添加了从ai 获得的代码。
if (/\d/.test(nama_siswa)) {
isValid = false;
// Display an error message using SweetAlert
Swal.fire({
icon: 'error',
title: 'Error',
text: 'number is not allowed in student name.'
});
}
这是我添加该代码后的代码。
if (step === 2) {
// Example: check if username is not empty
var student_name = document.querySelector('#student_name').value;
if (student_name === '') {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Field still empty'
});
} else if (student_name.length < 3 || student_name.length > 30) {
isValid = false;
Swal.fire({
icon: 'info',
title: 'the character must <3 or >30'
});
}
// new added code (start)
else if (/\d/.test(nama_siswa)) {
isValid = false;
// Display an error message using SweetAlert
Swal.fire({
icon: 'error',
title: 'Error',
text: 'number is not allowed in student name'
});
}
// new added code (end)
else
var student_email = document.querySelector('#student_email').value;
if (student_email === '') {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Field still empty'
});
} else if (!student_email.includes('@')) {
isValid = false;
Swal.fire({
icon: 'error',
title: 'Email must include "@"'
});
}
}
但它不起作用 - 没有错误消息。
我认为错误在于变量名nama_siswa。
相反,您应该使用 Student_name 作为变量来使用表示 0 到 9 的数字的正则表达式 /d 进行测试。
所以你的代码应该是这样的:
// new added code (start)
else if (/\d/.test(student_name)) {
isValid = false;
// Display an error message using SweetAlert
Swal.fire({
icon: 'error',
title: 'Error',
text: 'number is not allowed in student name'
});
}
// new added code (end)