[javascript] validation of input text field in html using javascript

<script type='text/javascript'>   
function required()  
{
    var empt = document.forms["form1"]["Name"].value; 
    if (empt == "")  
    {  
        alert("Please input a Value");  
        return false;  
    }  
}  
</script> 

<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />

I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.

This question is related to javascript html validation form-submit

The answer is


<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 

</script>




before using above code you have to add the gen_validatorv31.js js file

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Validation</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            var tags = document.getElementsByTagName("input");
            var radiotags = document.getElementsByName("gender");
            var compareValidator = ['compare'];
            var formtag = document.getElementsByTagName("form");
            function validation(){
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    //Validation for Textbox Start
                    if(tags[i].type == "text"){
                        if(tagval == "" || tagval == null){
                            var lbl = $(tags[i]).prev().text();
                            lbl = lbl.replace(/ : /g,'')
                            //alert("Please Enter "+lbl);
                            $(".span"+tagid).remove();
                            $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
                            $("#"+tagid).focus();
                            //return false;
                        }
                        else if(tagval != "" || tagval != null){
                            $(".span"+tagid).remove();
                        }
                        //Validation for compare text in two text boxes Start
                        //put two tags with same class name and put class name in compareValidator.
                        for(var j=0;j<compareValidator.length;j++){
                            if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
                                if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
                                    $("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
                                    $("span").prev("span").remove();
                                    $("."+compareValidator[j]+":last").focus();
                                    //return false;
                                }
                            }
                        }
                        //Validation for compare text in two text boxes End
                        //Validation for Email Start
                        if((tagval != "") && (tagclass.indexOf('email') != -1)){
                        //enter class = email where you want to use email validator
                            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                            if (reg.test(tagval)){
                                $(".span"+tagid).remove();
                                return true; 
                            }
                            else{
                                $(".span"+tagid).remove();
                                $("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
                                $("#"+tagid).focus();
                                return false;
                            }
                        }
                        //Validation for Email End
                    }
                    //Validation for Textbox End
                    //Validation for Radio Start
                    else if(tags[i].type == "radio"){
                    //enter class = gender where you want to use gender validator
                        if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
                            $(".span"+tagid).remove();
                            //$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
                            $(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
                            $("#"+tagid).focus();
                            i += 1;
                        }
                        else{
                            $(".span"+tagid).remove();
                        }
                    }
                    //Validation for Radio End              
                    else{

                    }
                }
                //return false;
            }
            function Validate(){
               if(!validation()){
                    return false;
                }
                return true;
            }
            function onloadevents(){
                tags[tags.length -1].onclick = function(){
                    //return Validate();
                }
                for(var j=0;j<formtag.length;j++){
                    formtag[j].onsubmit = function(){
                        return Validate();
                    }
                }
                for(var i=0;i<tags.length;i++){
                    var tagid = tags[i].id;
                    var tagval = tags[i].value;
                    var tagtit = tags[i].title;
                    var tagclass = tags[i].className;
                    if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
                        //enter class = numeric where you want to use numeric validator
                        document.getElementById(tagid).onkeypress = function(){
                            numeric(event);
                        }
                    }
                }
            }
            function numeric(event){
                var KeyBoardCode = (event.which) ? event.which : event.keyCode; 
                if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
                    event.preventDefault();
                    $(".spannum").remove();
                    //$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
                    //$(".numeric").focus();
                    return false;
                }
                    $(".spannum").remove();
                    return true;
            }
            if (document.addEventListener) {
              document.addEventListener("DOMContentLoaded", onloadevents, false);
            }
            //window.onload = onloadevents;
        </script>
    </head>
    <body>
        <form method="post">
            <label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
            <label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
            <label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
            <label for="gender">Gender : </label>
            <input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
            <input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
            <label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
            <label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
            <input type="submit" id="sub" value="Submit">
        </form>
    </body>
</html>

function hasValue( val ) { // Return true if text input is valid/ not-empty
    return val.replace(/\s+/, '').length; // boolean
}

For multiple elements you can pass inside your input elements loop their value into that function argument.

If a user inserted one or more spaces, thanks to the regex s+ the function will return false.


For flexibility and other places you might want to validated. You can use the following function.

`function validateOnlyTextField(element) {
    var str = element.value;
    if(!(/^[a-zA-Z, ]+$/.test(str))){
        // console.log('String contain number characters');
        str = str.substr(0,  str.length -1);
        element.value = str;
    }
}`

Then on your html section use the following event.

<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />

You can always reuse the function.


<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
  <p>
    1.word should be atleast 5 letter<br>
    2.No space should be encountered<br>
    3.No numbers and special characters allowed<br>
    4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
  </p>
  <button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>


validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 5) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 5 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    }else if(!(/^[a-zA-Z]+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'Only alphabets allowed'
    }
    else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'per 3 alphabets allowed'
    }
    else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }       

}

.error {
color: #E00000;
 }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to form-submit

Setting onSubmit in React.js Jquery function BEFORE form submission How to locate and insert a value in a text box (input) using Python Selenium? Submit form without reloading page How to check if text fields are empty on form submit using jQuery? Submitting HTML form using Jquery AJAX Serializing and submitting a form with jQuery and PHP How do I use an image as a submit button? How to pass value from <option><select> to form action validation of input text field in html using javascript