Validate a form using JavaScript

前端 未结 3 1304
长情又很酷
长情又很酷 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 22:08

    
    
    
    
    
    
    First name:
    ​​​​​​​​​​​​​​​​​​​

    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

提交回复
热议问题