1

I've got an assignment I'm working on. I'm required to use Javascript, not jQuery to validate a form and then submit that form to a PHP file using AJAX.

I've identified the JS functions (required fields, phone, email format) I want to use but not sure of the best method for activating those functions.

In addition I want to have the error message populate near the field rather than as a pop up.

It's not working in JSfiddle right now. I'm getting a forbidden 403 error.

The form:

<form id="contact-form" name="contact" onsubmit="return validateFormOnSubmit(this)" action="form.php" method="post">
        <h2>Contact Me</h2>
        <div>
            <label>Name</label>
            <input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
        </div>

        <div>
            <label>Email</label>
            <input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
        </div>

        <div>
            <label>Phone</label>
            <input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
        </div>

        <div>
            <input type="submit" name="submit" id="submit" tabindex="5" value="Send" />
        </div>

    </form>

The JS:

function validateFormOnSubmit(contact) {
var reason = "";

  reason += validateEmail(contact.email);
  reason += validatePhone(contact.phone);
  reason += validateEmpty(contact.name);

  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  return true;
}

// validate required fields
function validateEmpty(name) {
    var error = "";

    if (name.value.length == 0) {
        name.style.background = 'Yellow'; 
        error = "The required field has not been filled in.\n"
    } else {
        name.style.background = 'White';
    }
    return error;   
}


// validate email as required field and format
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
} 

function validateEmail(email) {
    var error="";
    var temail = trim(email.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (email.value == "") {
        email.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(temail)) {              //test email for illegal characters
        email.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (email.value.match(illegalChars)) {
        email.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        email.style.background = 'White';
    }
    return error;
}

// validate phone for required and format
function validatePhone(phone) {
    var error = "";
    var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (phone.value == "") {
        error = "You didn't enter a phone number.\n";
        phone.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        phone.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        phone.style.background = 'Yellow';
    } 
    return error;
}

Thanks for any help!

justinae
  • 387
  • 1
  • 2
  • 14
  • 1
    What exactly is your question? – Bergi Feb 18 '14 at 20:14
  • Is the method I'm using a good practice for calling up a JS function? Can I use this method with AJAX? Why am I getting a 403 error? – justinae Feb 18 '14 at 20:45
  • 1
    It's not the best practice, [installing the handler by JS](http://quirksmode.org/js/events_tradmod.html) would be better. Yes you can use ajax from an event handler. The 403 error is specific to jsfiddle - you must not submit forms there. To make your handler work, see [this question](http://stackoverflow.com/q/5431351/1048572) – Bergi Feb 18 '14 at 20:52
  • I have tweaked your [JSFiddle a bit so should now work](http://jsfiddle.net/tX5y5/11/). JSFiddle doesn't like form POSTs so I have disabled it - even on success. It now pops up and nice alert on success instead. As for displaying errors by each input that should be straightforward. You need to take each error and insert it into a `

    `, `` or other tag next to/near your input. Look into `innerHTML` property.

    – Etzeitet Feb 18 '14 at 20:59
  • Thanks. I just saw that I left out the onsubmit in my HTML. So is using 'onsubmit="return validateFormOnSubmit(this)"' the rigtht way? Perhaps a different question, but how do I use AJAX from the event handler? I changed JSfiddle to "no-wrap" and that worked. Bergi, submit an answer so I can accept it. Thanks! – justinae Feb 18 '14 at 21:06
  • @PeterSpain Your example, but avoiding inline JS: http://jsfiddle.net/tX5y5/19/ (as suggested by Bergi) – feeela Feb 18 '14 at 21:44
  • Oh I see how that is cleaner. The jsfiddle is still producing 403 error though. I've got the innerHTML piece working. Once we get the 403 figured out I think we'll be in business. – justinae Feb 18 '14 at 22:06
  • I've got it working with inline JS and innerHTML here. I set the return to false in the validateFormOnSubmit function to settle JSfiddle. http://jsfiddle.net/justinae/tX5y5/ – justinae Feb 18 '14 at 22:15

0 Answers0