I am a beginner JS student and attempting to do some form validation and I am struggling with it. I am currently suffering from covid so my brain may not be functioning and thinking through this properly but I need some help.
Basically what I am trying to test is that the "name" field of my form isn't blank AND that a number has not been input. I can get the blank part to check just fine but the number part is throwing me off. Here is the code I am working with.
function validateForm() {
let x = document.forms["contact_form"]["myName"].value;
if ((x == "") && (typeof x == 'number')) {
alert("Name must be filled out properly.");
return false;
}
}
Following suggestions.. It would seem I am not accessing form data properly. Here is the form data I am attempting to access:
<form class="contact_form" method="put" action="confirmation.html">
<label for="myName">Name:</label>
<input type="text" name="myName" id="myName" required />
Thank you for any and all help!
CodePudding user response:
Since you are using &&
, condition is guaranteed to evaluate false
. You should use OR (||
) operator here.
Also, the the type of the value of x
is string always string, you have to cast the value to number before the comparison, you can do so by prefixing
to the variable:
if ((x == "") || (typeof x == 'number')) {
Though, I will suggest you to use use isNaN()
if ((x == "") || !isNaN(x)) {
Demo:
function validateForm() {
let x = document.forms["contact_form"]["myName"].value;
if ((x == "") || !isNaN(x)) {
alert("Name must be filled out properly.");
return false;
}
}
<form name="contact_form">
<input name="myName">
<button onclick="return validateForm()">Click</button>
</form>