Javascript Form Validation Problem
i'm trying to put together some Javascript form validation to check that all fields have been completed before submitting.
So far i have this in my tag, and the function for the first form field only:
<script type="text/javascript">
function validate(form) {
fail = vaildatecompany_name(preview.company_name.value)
if (fail =="" return true
else { alert(fail); return false }
}
function validatecompany_name(field) {
if (field == "" return "No Company Name was entered. \n"
return ""
}
</script>
And the first field i'm trying to validate is:
<form action="jobpreview.php" name = "preview" method="post" form enctype="multipart/form-data" onSubmit = "return validate(this)">
<ul>
<li><label for = "company_name">Company Name</label>
<input type="text" name="company_name"/>
</li>
Can someone explain what i'm doing wrong? It's not bringing up any alert when i submit the form with no entry in the field and is just goi开发者_C百科ng through as normal.
Thanks Dan
Your code is riddled with errors. You spelled your call to the validatecompany_name
function wrong, your if
statements aren't properly formed (errant opening bracket) and you don't pass the form
variable properly (you treat preview
and form
interchangeably). This works, although it's not great code:
function validate(form){
var fail = validatecompany_name(form.company_name.value);
if (fail==""){
return true;
} else {
alert(fail);
return false;
}
}
function validatecompany_name(field){
if (field == "") return "No Company Name was entered. \n";
return "";
}
You need closing parentheses on your if statements if (BOOLEAN)
Plain and un-fancy javascript validation:
<script type="text/javascript">
function validate(form) {
var company_name=form.company_name;
if (company_name.value=="") {
alert("Please enter company name");
company_name.focus();
return false
}
var company_phone=form.company_phone;
if (company_phone.value=="") {
alert("Please enter company phone");
company_phone.focus();
return false
}
return true; // allow submission
}
</script>
<form action="jobpreview.php" method="POST"
enctype="multipart/form-data" onSubmit="return validate(this)">
<ul>
<li><label for = "company_name">Company Name</label>
<input type="text" name="company_name"/>
</li>
.
.
.
</form>
If you need anything fancier than that, look at jQuery validation instead
wat is this statement do proper closings... if (field == "" return "No Company Name was entered. \n"
it should be like if (field == "") return "No Company Name was entered. \n"
and you cannot directly access form by name.. use document.formname
or use the form object that you passed...
精彩评论