开发者

how to validate a form using JavaScript? [closed]

开发者 https://www.devze.com 2023-03-14 18:37 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Say I have a form with a few textFields and a submit button.

What would be the best way, once the user clicks this button,开发者_Go百科 for javascript to validate the textFields ( at least, make sure there's something in there ) and, if not, pop out a message, if everything OK, the submit the form and php will take over.

Thanks!


add an OnClick="function_name();" in the html of your submit button,

and in the declaration of the function do this

function function_name(){
     var str = document.getElement("your_text_field_id");
     if (str=="") {
       alert("Please type some text first");
       return false
     } else { 
       alert("Thanks");  //optional
       return true;
     }
}


Call a JavaScript function which validates user input fields using the forms onSubmit method.


If you are using jQuery (if not, you should) you can do something when the form gets submitted through .submit(). Within this event you can check all the input fields depending on their type, if an error occurs you can call event.preventDefault() to stop the submitting and alert() an error.

Something like this:

<form id="myform">
    <input type="text" name="text" />
    <input type="submit" value="Submit!" />
</form>

jQuery:

$('#myform').submit(function(event){

    error = false;

    $('input',this).each(function(){

        if($(this).val() == '')
            error = true;

    });

    if(error == true){

        event.preventDefault();
        alert('An error occured!');

    }

});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号