Chapter 5 Exercise Set 1

  1. Being able to read the values of the form fields makes it possible to write a function validInfo, which takes a form object as its argument and returns a boolean value: true when the name field is not empty and the email field contains something that looks like an e-mail address, false otherwise. Write this function.

    function validInfo(form) {
        return form.elements.name.value != "" &&
            /^.+@.+\.\w{2,3}$/.test(form.elements.email.value);
    }
    
    alert(validInfo(document.forms.userinfo));
    

    You did think to use a regular expression for the e-mail check, didn’t you?

  2. Finish the form validator by giving the button’s onclick property a new value ― a function that checks the form, submits when it is valid, or pops up a warning message when it is not. It will be useful to know that form objects have a submit method that takes no parameters and submits the form.

    userForm.elements.send.onclick = function() {
        if (validInfo(userForm))
            userForm.submit();
        else
            alert("Give us a name and a valid e-mail address!");
    };