how to validate a form using JavaScript? [closed]
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!');
}
});
精彩评论