JavaScript Form Validation

hello guys in this tutorial i'm going to show you form validation using
javascript  

step 1:
create index.html file 

step 2:
create validate.js


here is the code 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatiblecontent="IE=edge">
    <meta name="viewportcontent="width=device-width, initial-scale=1.0">
    <title>validation</title>
    <link rel="stylesheethref="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.cssintegrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXmcrossorigin="anonymous">
</head>
<body>
    <style>
        body{
            font-size: 18px;
            text-transform: capitalize;
            margin: 20px;
        }
        #success{
       color:green;
        }
        #warn{
            color: red;
        }
    </style>
    <h1>js validation</h1>
    <form action=""autocomplete="off">
        <div class="form-group">
            <label for="">name</label>
            <input type="textclass="form-controlid="name">
            <span id="name-error"></span>
        </div>
        <div class="form-group">
            <label for="">phone number</label>
            <input type="textclass="form-controlid="number">
            <span id="number-error"></span>
        <div class="form-group">
            <input type="submitclass="btn btn-primary"id="submitdisabled>
        </div>
    </form>
</body>
<script src="validate.js"></script>
</html>



validate.js


var btn=document.querySelector("#submit");
var names=document.getElementById("name");
var number=document.querySelector("#number");
var name_alert=document.querySelector("#name-error");
var number_alert=document.querySelector("#number-error");
names.addEventListener('keypress', function(e){
    console.log(names.value);
    let newname=names.value;
  console.log(newname);
    if(newname.length>8)
    {
   name_alert.innerHTML=`<p id="success">valid name </p>`;
   btn.removeAttribute("disabled");
    }
    else{
        name_alert.innerHTML=`<p id="warn">password length should be 8</p>`;
        btn.setAttribute("disabled", true);
    }
});
number.addEventListener('keyup', function(){
  let newnumber=number.value;
  //alert("asdf");
  var pattern = /^[6-9]\d{9}$/ ;
    if(pattern.test(newnumber))
    {
   number_alert.innerHTML=`<p id="success">valid number </p>`;
   btn.removeAttribute("disabled");
    }
    else{
        number_alert.innerHTML=`<p id="warn">phone number should be 10</p>`;
        btn.setAttribute("disabled", true);
    }
})
btn.addEventListener('click',function()
{
  alert("click");
})

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post