JS ファイルをリンクして入力を検証することにより、ユーザーの入力を検証しようとしています。ただし、間違ったデータで送信ボタンをクリックすると、フォームが送信され、検証エラーは発生しません。
フォーム:
<form id="user_form" name="contactForm" action="#" method="GET" onsubmit="return validateForm();">
<p id="first_name" class="input_title">First name <span class="asterisk_red">*</span></p>
<!-- The HTML 5 'Required' attribute will not allow the form to be sent empty. -->
<input class="input_box" type="text" name="first_name" placeholder="Joe" />
<input id="submit_button" type="submit" name="submit" value="Submit"/>
</form>
そして、検証に使用する JS:
function validateForm(){
/* Validate the first name field of the form */
var fn = document.forms['contactForm'].first_name.value;
/* If the Name string is empty then return false and show warning. */
if (fn == ""){
alert("First name must be filled out");
document.forms['contactForm'].first_name.reset();
return false;
}else if(fn.length <= 2){
alert("Your first name must more than two characters");
document.forms['contactForm'].first_name.reset();
return false;
}
}