Validate a form using JavaScript

前端 未结 3 1303
长情又很酷
长情又很酷 2021-01-26 21:09

I am a beginner and I have written a code for validating the form as:

function validateForm(){
var x=document.forms[\"myForm\"][\"fname\"].value;
if (x==null ||          


        
相关标签:
3条回答
  • 2021-01-26 21:43

    This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:

    <script>
    function validate(){
    var y = document.getElementById("errorResponse");
    var x=document.forms["myForm"]["fname"].value;
        if (x==null || x==""){
            y.innerHTML = "Error";
        }
    }
    </script>
    

    The HTML form is:

    <form name="myForm">
    First name: <input type="text" name="fname" onBlur = "validate()">
    <div id = "errorResponse"></div>
    <input type="submit" value="Submit">
    </form>
    

    The div can be designed in CSS to red color to get user attention and many more tricks can be played.

    0 讨论(0)
  • 2021-01-26 21:48

    replace your input element's code by following

    <input type="text" onblur="return validateForm();" name="fname">
    

    i guess thats what you are looking for

    0 讨论(0)
  • 2021-01-26 22:08
    <html>
    <head>
    <script type="text/javascript">
          function validateForm(oForm){
        var els = oForm.elements;
        for(var i = 0; i < els.length; i++){
           if('string' === typeof(els[i].getAttribute('data-message'))){
              return valEl(els[i]);
           }
        }
    } 
    
    function valEl(el){
        var method = el.getAttribute('data-valMethod');
        if('req' === method && (el.value === null || el.value === '')){
               alert(el.getAttribute('data-message'));
               return false;
        }
    } 
    </script>
    </head>
    <body>
    <form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
    First name: 
        <input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
    <input type="submit" value="Submit">
    </form>
    </body>
    
    </html>​​​​​​​​​​​​​​​​​​​
    

    I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
    Since HTML5 the Data-* attributes are very handy for these things :-)

    This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.

    From here you can expand the valEl-function to accommodate other types of validation.

    Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.

    Happy coding. /G

    PS http://jsfiddle.net/ePPnn/11/ for sample code

    0 讨论(0)
提交回复
热议问题