Question

I'm trying to stop people from sending me blank emails through my contact us on my website. On my main website I have succeeded with the following javascript:

<script type="text/javascript">
function checkForm(f)
{
if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" &&          f.elements['cf_message'].value == "")
{
    alert("You have not filled in all of the required fields.");
    return false;
}
else
{
    f.submit();
    return false;
}
}
</script>

Although this works, when I implemented the same on my mobile website, people are still able to send blank emails.

The HTML code I used for the form check is:

<form action="contact.php" method="post" name="sform" onSubmit="return checkForm(this);">

So my question is how do i stop form submission if the fields are empty, on a mobile device (specifically iPhone)

Was it helpful?

Solution

Are you sure this isn't a logic error? Seems like this:

if (f.elements['cf_name'].value == "" && f.elements['cf_email'].value == "" &&          f.elements['cf_message'].value == "")

Should be:

if (f.elements['cf_name'].value == "" || f.elements['cf_email'].value == "" ||          f.elements['cf_message'].value == "")

OTHER TIPS

Although client-side validation is useful because it's more immediate, you should never rely on it, and using Javascript alone to do this sort of check is riddled with holes (as you found). Write code which will work nicely if Javascript works, and will still do the validation you want if Javascript is not implemented.

Since you are sending your form data to a php script, do your checking there as well as in the client and only send the mail if the form data is valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top