[我正在尝试进行js表单验证检查,但是由于某些原因,当我在编写函数时这里没有发生任何变化,因此当我的电子邮件值为“”时,它应该显示警报消息,但不显示:
<form onsubmit="checkForm()" method="post">
<input class="test" type="text" minlength="1" maxlength="10" name="firstname" placeholder="➡️ Write Your First
Name"></input>
<input class="test" type="text" name="lastname" placeholder="😊 Write your Last Name"></input>
<input class="test" id="email" type="email" name="email" placeholder="✉️ Write your Best Email"></input>
<!--<textarea class="test" type="text" name="comment" placeholder="Tell us more about yourself"></textarea>-->
<script>
function checkForm(form) {
const getEmailValue = document.getElementById(email);
if (getEmailValue === "") {
alert('you need to fullfill');
}
}
</script>
<div id="buttoncenter">
<button type="submit" class="button">SUBMIT</button>
您需要引用getElementById
的参数,并获取value
属性。
当不应该提交表单时,验证功能还应该返回false
,并且您需要在return
中使用onsubmit
语句以便可以使用。
function checkForm(form) {
const getEmailValue = document.getElementById('email').value;
if (getEmailValue === "") {
alert('you need to fullfill');
return false;
}
}
<form onsubmit="return checkForm()" method="post">
<input class="test" type="text" minlength="1" maxlength="10" name="firstname" placeholder="➡️ Write Your First
Name"></input>
<input class="test" type="text" name="lastname" placeholder="😊 Write your Last Name"></input>
<input class="test" id="email" type="email" name="email" placeholder="✉️ Write your Best Email"></input>
<input type="submit">
</form>