Skip to main content

How to create a form and validate the form?

 In this blog we will validate our form by using pure javascript..firstly we have to 

make our form in HTML and apply some basic css design so that it looks nice.

<!-- Data Validation
Data validation is the process of ensuring that user input is clean, correct, 
and useful.

Typical validation tasks are:

has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different 
ways.

Server side validation is performed by a web server, after input has been sent to 
the server.

Client side validation is performed by a web browser, before input is sent to a 
web server. -->



Inside the body of our HTML we make a form tag and while on submit the form we return a validateform() function 

which validate our form and we are going to write this function in our js file 

here we make a separate js file so don't forget to add it.


"index.html"


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>form validation</title>
</head>
<style>
    body {
        padding20px;
        background-coloraqua;

    }

    .formdesign {
        font-size20px;
        margin-topauto;
        padding-top20px;
    }

    .formdesign input {
        width50%;
        padding12px 20px;
        border1px solid blue;
        margin14px;
        border-radius4px;
        font-size15px;
    }

    div.hello {
        margin-top50px;
        margin-left80px;
        border-radius:2px;
    }
    .formerror{
        color:red;
    }

    .but {
        border-radius9px;
        width100px;
        height50px;
        font-size25px;
        margin22px 20px;
    }
</style>

<body>
    <form name="myForm" onsubmit="return validateform()" method="post">
        <div class="hello">
            <div class="formdesign" id="name">
                Name: <input type="text" name="fname"><b>
            <span class="formerror"></span></b>
            </div>
            <div class="formdesign" id="email">
                email: <input type="email" name="femail"><b>
            <span class="formerror"></span></b>
            </div>
            <div class="formdesign" id="phone">
                phone no: <input type="phone" name="fphone" required><b>
            <span class="formerror"></span></b>
            </div>
            <div class="formdesign" id="pass">
                password: <input type="password" name="fpass"><b>
            <span class="formerror"></span></b>
            </div>
            <div class="formdesign" id="phone">
                confirm password: <input type="password" name="fcpass"><b>
            <span class="formerror"></span></b>
            </div>
             <input class="but" type="submit" value="submit">

        </div>

    </form>
</body>
<script src="form.js"></script>

</html>



In the js file we also make 2 functions clearErrors() and seterror().In the validateform() function first we call the 
clearErrors() function so that if there are any errors in our form than it will iterate the errors and loop it 
for(let item of errors)
    {
        item.innerHTML = "";
    }
and set the innerHTML of this to blank.so that the errors will be gone.
and in the seterror() function we take two arguments id and error and set the error to the respective id.

"form.js"

function clearErrors(){
    errors = document.getElementsByClassName('formerror');
    for(let item of errors)
    {
        item.innerHTML = "";
    }
}
function seterror(iderror){
    //sets error inside tag of id 
    element = document.getElementById(id);
    element.getElementsByClassName('formerror')[0].innerHTML = error;

}

function validateform(){
    var returnval = true;
    clearErrors();

  //perform validation and if validation fails, set the value of returnval to false
    var name = document.forms['myForm']["fname"].value;
    if (name.length<5){
        seterror("name""*Length of name is too short");
        returnval = false;
    }

    if (name.length == 0){
        seterror("name""*Length of name cannot be zero!");
        returnval = false;
    }

    var email = document.forms['myForm']["femail"].value;
    if (email.length>15){
        seterror("email""*Email length is too long");
        returnval = false;
    }

    var phone = document.forms['myForm']["fphone"].value;
    if (phone.length < 10){
        seterror("phone""*Phone number should be of 10 digits!");
        returnval = false;
    }

    var phoneno= /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if(phone.match(phoneno)){
        returnval=true
    }
    else{
        seterror("phone","*phone no format not match")
        returnval=false

    }



    var password = document.forms['myForm']["fpass"].value;
    if (password.length < 6){

        // create a logic to allow only those passwords which contain 
atleast one letter, one number and one special character and one uppercase letter
        seterror("pass""*Password should be atleast 6 characters long!");
        returnval = false;
    }
var decimal1=  /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
        if(password.match(decimal1)){
            returnval=true
        }
        else{
            seterror("pass","*password should contain at least one lowercase letter,
 one uppercase letter, one numeric digit, and one special character")
            returnval=false
        }
    var cpassword = document.forms['myForm']["fcpass"].value;
    if (cpassword != password){
        seterror("cpass""*Password and Confirm password should match!");
        returnval = false;
    }

    return returnval;
}





Comments

Popular posts from this blog

currency converter code in python

 Hello guys, Today in this code i discuss how to convert any currency in python. This is an simple currency converter code. First we have to download the currency data from the google and don't worry i will also provide  this file.. "currency data" Argentine Peso 60.003324 0.016666 Australian Dollar 1.456434 0.686608 Bahraini Dinar 0.376000 2.659574 Botswana Pula 10.748595 0.093035 Brazilian Real 4.165726 0.240054 British Pound 0.769337 1.299820 Bruneian Dollar 1.347741 0.741982 Bulgarian Lev 1.764110 0.566858 Canadian Dollar 1.306715 0.765278 Chilean Peso 773.624384 0.001293 Chinese Yuan Renminbi 6.864835 0.145670 Colombian Peso 3332.909888 0.000300 Croatian Kuna 6.707817 0.149080 Czech Koruna 22.658193 0.044134 Danish Krone 6.740053 0.148367 Emirati Dirham 3.672500 0.272294 Euro 0.901975 1.108678 Hong Kong Dollar 7.769198 0.128713 Hungarian Forint 303.647304 0.003293 Icelandic Krona 123.937684 0.008069 Indian Rupe...

WHAT IS DJANGO AUTHENTICATION?AND HOW TO MANUALLY WRITE THE CODE FOR THE SIGNUP, LOGIN AND LOGOUT?

In this post we see how to manually write the code for the user Registeration , Login and Logout. firstly we have to start a project and than start an app:      django-admin startproject user-authentication     $ cd user-authentication     $ python manage.py startapp accounts Once we have created an app we have to add this app in the INSTALLED_APPS  in settings.py. Than we have to add the path of the accounts app: "main project urls.py" from  django.contrib  import  admin from  django.urls  import  path,include from  django.conf  import  settings urlpatterns = [     path( 'accounts/' ,include( 'accounts.urls' )),     path( 'admin/' , admin.site.urls), ] if  settings.DEBUG:     urlpatterns=urlpatterns+static(settings.MEDIA_URL, document_root =           settings.MEDIA_ROOT)   ...