I have this Form that works successfully (I know it's not state-of-the-art).
I simply want to add code to make Contact Name field mandatory. Can you help me?
I don't know how much code I should post. Here's some:

<script type="text/javascript">
function checkemail(){
var str=document.myform.email_address.value;
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (filter.test(str))
testresults=true;
else {
alert("Please input a valid email address!");
return false;
}
if(document.myform.agree.checked!=1) {
alert("Please check the box to agree to the Terms.");
return false;
}
if(document.myform.ans.value.toLowerCase()!="white") {
alert("Please answer security question correctly: Black or White?");
return false;
}
return true;
}
</script>

People can overide the JS, you must do it on the PHP side of things. But you can add in a bit of JS too just for looks:

// Your form:
<form blah blah onsubmit="checkfields()"></form>

// Your JS
var contact_name_value = document.getElementById('#contact_name').value
if(contact_name_value == '') {
    alert("Please enter a contact name!");
    return false;
}

there are many ways to do this:-

  • HTML5 has introduced a very useful attribute "required".If we add this attribute to any control(textbox,textarea...) ,then that field is mandatory.
    http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#attr-input-required
  • traditional javascript validation

    <script>
    var contact_name_value = document.getElementById('contact_name').value;//# not required.Semi colon missing
    if(contact_name_value == '') {
        alert("Please enter a contact name!");
        return false;
    }
    </script>
    <form onsubmit="checkfields()">
    <input type="text" name="contact_number" id="contact_name">
    <input type="submit">
    </form>
    

It depends on browser compactibility.html5 is supported by all modern browsers(chrome,firefox...).for IE version must be IE10

But again, people can easily overide these attributes and JS. You must also validate on PHP side.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.