Home > Net >  How to add a form validation using JavaScript?
How to add a form validation using JavaScript?

Time:03-30

I have 3 fields which I want to validate

<form name='Login' method='post' target='_self'>
      <div ...>
         <input id="accountLoginField"  type="text" name="account" value="" placeholder="">
         <input id="userLoginField"  type="text" name="user" value="" placeholder="">
         <input id="passLoginField"  type="password" name="password" value=""
                           placeholder=""> ....

And I have submit input

<input id="btn_login" type="submit" name="submit"  value="Connect">

   

How can I check if these fields are empty and show alert box? I tried diferent ways that I found here and on other sites, but none of them seems to work... Thank you

CodePudding user response:

You can validate using if and else and check with the values attribute like, this the sample code you can refer for,

        function validateform(){  
var name=document.myform.name.value;  
var password=document.myform.password.value;  
  
if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
  }  
}  
</script>  
<body>  
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >  
Name: <input type="text" name="name"><br/>  
Password: <input type="password" name="password"><br/>  
<input type="submit" value="register">  
</form>  

Likewise, you can check for every field.

CodePudding user response:

The following example will submit to a live test server and the response will be displayed in an <iframe> for demonstration purposes. Client side validation is minimal and of course the server should do the heavy lifting when it comes to validation. Here are the major points:

  1. Make sure the submit button is within the <form>. If for some reason it isn't, add form="*" to it ("*" is the id of <form>). Although it's totally valid for <form> to have a name, an id is more useful so in example <form id='login'...>.
  2. Each field has a required attribute so it can be validated when the "submit" event is triggered, the first blank <input> will have a popup.
  3. The first <input> type has been changed to "email" so validation will stop submission should the user forget @.

<form id='login' action='https://httpbin.org/post' method='POST' target='response'>
  <fieldset>
    <input name="account" type="email" placeholder="Email address" required>
    <input name="user" type="text" placeholder='User name' required>
    <input name="password" type="password" placeholder="Password" required>
    <input type="submit" value="Connect">
  </fieldset>
</form>
<label>These two buttons are outside of form.</label><br>
<input type='submit' form='login' value='Works'>
<input type='submit' value="Doesn't Work"><br>
<iframe name='response'></iframe>

  • Related