I have made a form as index.html. I have a from validation using JavaScript. When the submit button is clicked it must open another html page(detail.html). When I supply wrong data, it must prevent the opening of detail.html page and display the error messages but neither of them happens .
here is the code
<form action="/detail" method="POST" role="form" name="index" onsubmit="return validateForm()" enctype="application/x-www-form-urlencoded">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required/>
<span class="formerror"></span>
<br />
<label for="phone_number">Mobile:</label>
<input type="number" name="phone_number" placeholder="enter your mobile number" required >
<span class="formerror"></span>
<br/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="enter your password" required />
<span class="formerror"></span>
<br />
<button id="btnsubmit" class="btn" onclick="submit">Submit</button>
code for form validation
<script>
function clearErrors(){
errors=document.getElementsByClassname('formerror');
for(let item of errors){
item.innerHTML="";
}
}
function seterror(id,error){
//sets error inside tag of id
element=document.getElementById(id);
element.getElementsByClassName('formerror')[0].innerHTML=error;
}
function validateForm(){
var returnval = true;
//performs validation and if validation fails, set the value of returnval to false.
var name = document.forms['index']["name"].value;
if(name.length<3)
{
seterror("name","length of name of too short");
returnval=false;
}
var phone_number = document.forms['index']["phone_number"].value;
if(phone_number.length!=10)
{
seterror("phone_number","phone number should be of 10 digits");
returnval=false;
}
var password = document.forms['index']["password"].value;
if(password.length<4)
{
seterror("password","password should be at least of 4 characters");
returnval=false;
}
return returnval;
}
</script>
I wanted the index.html to display the error messages when wrong data is fed to the input fields, but nothing of those happens instead detail.html page opens. detail.html must only open when correct input is given.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/1x4cBp5
Comments
Post a Comment