This is the part of my multi-step registration form, and it working fine.
But I want to add a number validation to the "student_name" variable, so the system will prevent the student to input the number in their 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 "@"'
});
}
}
So I added this code that I got it from the 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.'
});
}
So this is my code after I add that code.
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 "@"'
});
}
}
But it didn’t work – there is no error message.
2
Answers
I think the mistake lies in the variable name nama_siswa.
Instead you should be using the student_name as the variable to test with the regex /d representing a digit from 0 to 9.
So your code should look like this:
HTML forms validate themself.
To valdiate if a name has a length of 3-30 charters you can add the
minlength="3"
andmaxlength="30"
attribtues.Emails can be validated if the input ahs the
type="email"
attribtue.All you need to do is to add the
required
attribtue to the inputs and it will even throw an localized error mesage that is depending on the suers system language:If you have a