RU beehive logo ITEC dept promo banner
ITEC 325
2018spring
ibarland

calling javascript
the mechanics of invoking from the browser

Review: We saw an example of javascript that was run by the browser; we defined the javascript functions in the head (or, in a separate file which was included via a <script src= > tag in the head). Then, in various tags we had onclick attributes, whose value was a bit of javascript code, which the browser then evaluated. (e.g. Whatever you do don't click <span onclick="explode();">here</span>.).

Other events that can invoke javascript: onchange, onclick, onfocus, onblur. See w3.org’s definition.

validating on the client-side, via javascript

Adding error messages dynamically

Suppose you have an a field named "age", which should be between at least 21, but not 40 or more1. We've already seen that we want to validate this both by the input tag's onchange, as well as by the form tag's onsubmit. So we definitely want to avoid the repeated code.

function validateAge() {
    var ageNode = document.getElementById('age');
    var age = ageNode.value;
    var isValid = (21 <= age && age < 40);

    var ageErrMsgNode = document.getElementById('ageErrMsg');
    if (!isValid) {
        ageErrMsgNode.innerHTML = "Must be between 21 (inclusive) and 40 (non-inclusive)";
        // Hmm, might be nice to include the offending value in the error msg?
        }
    return isValid;
    }

Things to consider:

the example form (a repeat of previous link)

Improved version: Have a validation-function “validateAgeErrMsg” which just returns the error-message-string (perhaps the empty-string, if no error); have a separate function “insertErrMsg” that takes a node and a message, and splices that message-text into the DOM for that node, with a style that indicates an error message2 (perhaps small but angry red font).

You can also see w3.org’s definition of the insertAdjacentHTML method.

Structure of validation code

validating on the client-side, via html5 attributes

A lot of validation can be done with html5 attributes. This can shorten — or even eliminate — the need for individual validation functions. And if no individual validation functions are needed, then a validateAll isn't either!

youtube (20m57s):

You should prefer using the built-in validation, over rolling-your-own javascript to do the same. Even if you have a nicer way of presenting the information, there is strength in having the user see error messages always presented in the same way across all their sites. It also enables users to configure browser shortcut/hotkeys, plug-ins, etc. to improve their experience on your site.4 The one thing I miss (as of Chrome v56.0, 2017-Mar) is that browser-validation-errors tends to only get revealed one-by-one, as the submit button is pressed, whereas I'd prefer them to be revealed instantly onchange. But, a future version of the browser might well fix this.

Gotchas about validating regular-expressions in html

  1. The pattern attribute is ignored if the input is (a) left empty and (b) not required='required'.
    (Kinda makes sense-ish: if it's not required, then the empty string is valid, regardless of any pattern.)
  2. The pattern applies to the entire string; no need to anchor the pattern with ^ or $.
    (Use .* on either side, to effect “the string contains a pattern-match”.)
  3. No need to: quote back-slashes: pattern="\w+" is fine, you don't need pattern="\\w+". (After all, our html file is a string; backslash has no special meaning inside an html file, except for embedding single-quotes within a double-quoted string or vice-versa).
  4. No need to: use starting/ending slashes, for the pattern attribute. (We're not writing php or javascript.) So pattern="so\w+in." will pass, when the input is “somestring”.
    (On the other hand, if/when we are inside a script tag, then javascript rules apply: <script type="text/javascript"> "somestring".match(/^so\w+in.$/); </script>.5)
  5. The regexp support may be a bit wonky, and might (in reality) differ from one browser to another. In particular, when using Chrome (v56.0…, 2017-Mar-19) the regex pattern='.{3}+' did not prohibit “abcd”, but pattern='(.{3})+' did:
    Strings of multiples-of-length-3:
    pattern: .{3}+
    pattern: (.{3})+
    (really submit?)

1 That is, the half-open range [21,40) — half-open ranges are the right way to deal with integer ranges.      
2 Or even better: a “insertMsg” which includes a boolean -- should the message be inserted with a style of “error-occurred” or a style of “all-okay” (which might render in small happy green font).      
3 Well, it's not clear to me that if you're very clever, and use some sort of “cryptographically-obfuscated” javascript and submitted-info, you might be able to keep an attacker from bypassing the validation and submitting doctored values.      
4 An ibarland pet-peeve: login pages that use javascript instead of standard input forms; my password-manager can't easily auto-fill customized javascript, making those pages noticeably more painful to use.      
5 Just to make sure you're confused: Inside javascript, where regexp literals start/end with a slash, you don't need to quote the backslash like you do in (say) a java string-literal. So the /so\w+in./ is fine javascript, and is the equivalent of new java.util.regex.Pattern("^so\\win.$").      

logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated 2018.Mar.19 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.