辅导案例-IERG4210

欢迎使用51辅导,51作业君孵化低价透明的学长辅导平台,服务保持优质,平均费用压低50%以上! 51fudao.top
IERG4210 Web Programming and Security
Forms I - Client-side Implementations
Kehuan Zhang
Fall, 2019
Dept. of Information Engineering
The Chinese University of Hong Kong
Adapted from materials prepared by Dr. Adonis Fung
1231
Agenda
HTML: Forms Basics, Input Controls
Client-side Restrictions
HTML: The use of form elements
HTML: HTML5 Validations
JS: Javascript Validations
Form Submission Approaches
Traditional Form Submission
Programmatic Form Submission
AJAX Form Submission
2

Personal Information



  • />




  • name="gender" value="M" /> M name="gender" value="F" /> F




  • required="true" placeholder="[email protected]" />




  • Personal Information
    Name*
    Gender*
    M F
    Email*
    [email protected]
    Address*
    Region*
    Send * denotes a
    required field.
    HTML Forms
    The prevalent approach to solicit information from users
    Technically, a tag that comprises different form controls
    including , Description:
    text to be
    displayed
    Photos: Photos:
    Browse… No file selected.
    Go

    Form Controls (3/4)
    Even More Controls:
    Textarea (Multi-line text field)
    File Field
    Submit Button
    Submit Image Button (Image Credit: HSBC)
    7
    Email:* required="true" />
  • Email:*

    URL:

    URL:
    placeholder="Search..." />
    Search...
    Amount: $pattern="^[\d,.]+$" />
    Amount: $
    Form Controls (4/4)
    HTML 5 New Controls
    Email and Date Field
    URL Field with optional use of styling by new CSS selectors
    Search Field
    Custom Pattern Field with regular expressions
    In a nutshell, HTML5 Forms introduced
    Tags with more semantic information: Built-in support of client-side validations
    New CSS Pseudo Selectors: :valid, :invalid, :required and :optional
    8
    Regular Expressions
    A language to recognize string patterns
    Refer to a Cheatsheet for reference
    What you must know:
    ^ - start of string; $ - end of string (IMPORTANT to validations!)
    + - one or more times; ? - 0 or 1 times; * - 0 or more times
    Examples:
    Float (\d includes digits only):
    ^[\d\.]+$
    Alphanumeric (\w includes letters, digits, underscore):
    ^[\w\-, ]+$
    Email:
    ^[\w\-\/][\w\'\-\/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$
    The regular expression for email address is readily available on Web.
    IMPORTANT: Consult creditable websites for reusable patterns!!
    9
    HTML5 Forms: Browser Support (1/2) - Types
    MENU LOGIN
    The introduction
    HTML5 is the newest specification for HTML, the language that web browsers read to display web pages.
    HTML5 has many new features intended to make creating websites easier and people’s experience in using
    those websites better. Among those features are many enhancements to web forms.
    Support for HTML5 web form features is improving, but not all web browsers support HTML5 features the
    same way. This page is intended to explore those new new features and help you understand which browsers
    are supporting which features and to what degree. As a whole, this represents the current state of HTML5
    forms. But, even if you still need to support older browsers which don’t support all the new features, realize
    The Current State of HTML5 Forms
    Let's explore the different features of HTML5 forms.
    https://wufoo.com/html5/#types 10
    HTML5 Forms: Browser Support (2/2) -
    Attributes
    MENU LOGIN
    The introduction
    HTML5 is the newest specification for HTML, the language that web browsers read to display web pages.
    HTML5 has many new features intended to make creating websites easier and people’s experience in using
    those websites better. Among those features are many enhancements to web forms.
    Support for HTML5 web form features is improving, but not all web browsers support HTML5 features the
    same way. This page is intended to explore those new new features and help you understand which browsers
    are supporting which features and to what degree. As a whole, this represents the current state of HTML5
    forms. But, even if you still need to support older browsers which don’t support all the new features, realize
    The Current State of HTML5 Forms
    Let's explore the different features of HTML5 forms.
    11
    Client-side Restrictions
    To inform the users early on for input errors
    To create a more interactive and responsive UI experience
    Otherwise, input errors are prompted only after form
    submissions (round-trip delay)
    To imply a specific pattern that a user is expected to follow
    To help users enter/choose the valid data that we need
    IMPORTANT: Yet, these restrictions can be bypassed by
    Parameter Tampering Attacks!! Don't count on them for
    security!! Reason: A user has full control of any client-side
    code downloaded to his browser using the lovely Firebug :)
    Hence, you need input validations implemented on BOTH
    server-side for security enforcement, and
    client-side for better user experience.
    12
    3 Approaches of Client-side Restrictions
    The use of different form controls (shown in previous slide)
    e.g. Radioboxes for genders implies a restriction on only
    two possible values, i.e. M or F
    e.g. Dropdown menu implies a restriction on accepting
    some default choices
    1.
    Validations with HTML5 (shown in previous slide)
    The first built-in support of client-side validations by IE
    10+, Firefox 4+, Chrome, etc
    e.g. Email, URL, Search, and Custom fields as shown in
    previous slide
    2.
    Validations with Javascript (to be discussed in next slide)
    The programmatic way to customize input patterns
    Well-supported across browsers
    3.
    13
    Form Validations with Javascript (1/4)
    Strategy: Write your code in HTML5 for new browsers; Fallback
    to Javascript for legacy ones
    Given a form that has a HTML5 Email field,

    Email:

    Password:



    Note: Unsupported type will fallback to an ordinary textfield
    Add the title, HTML5 requried and pattern attributes

    Email: pattern="^[\w\-\/][\w\'\-\/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$" />

    Password: title="valid password" required="true"/>



    Note:
    Unsupported attributes will be ignored in legacy browsers
    The regular expression for email address is readily available on Web.
    IMPORTANT: Consult creditable websites for reusable patterns!! 14
    Form Validations with Javascript (2/4)
    To validate the form right before form submission:

    Email: pattern="^[\w\-\/][\w\'\-\/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$" />

    Password: title="valid password" required="true"/>



    15
    Form Validations with Javascript (3/4)
    With a HTML5-compilant browser, JS validation is ignored:
    Email:
    Password:
    Note: POST Parameters can be accessed only by server but not JS. Hence, nothing is
    shown here after submission. Firebug can show what was already sent.
    With HTML5 Validation disabled w/novalidate attribute:
    Using

    Email:
    Password:
    Note: Need some free old-school IE browsers for professional compatibility tests!?
    16
    Form Validations with Javascript (4/4)
    Recall the best practice: Graceful Degradation (Mentioned in
    Lecture 2)
    if (HTML5 supported) use the native HTML5 Validation
    else if (JS supported) use the JS validation code
    else the form still works without any validations
    Extend the code to also validate radio and checkbox
    for (var i = 0, p, el, els = this.elements; el = els[i]; i++) {
    // validate empty field, radio and checkboxes
    if (el.hasAttribute('required')) {
    if (el.type == 'radio') {
    if (lastEl && lastEl == el.name) continue;
    for (var j = 0, chk = false, lastEl = el.name, choices = this[lastEl],
    choice; choice = choices[j]; j++)
    if (choice.checked) {chk = true; break;}
    if (!chk) return displayErr(el, 'choose a ' + el.title);
    continue;
    } else if ((el.type == 'checkbox' && !el.checked) || el.value == '')
    return displayErr(el, el.title + ' is required');
    }
    if ((p = el.getAttribute('pattern')) && !new RegExp(p).test(el.value))
    return displayErr(el, 'in' + el.title);
    }
    Code Demo. A question: how to skip disabled/hidden controls??
    17
    3 Form Submission Approaches
    Traditional Form Submission (demonstrated in previous slide)
    Triggered by a submit button or the Enter key
    Fires the submit event, where one can validate before a form submission
    1.
    Programmatic Form Submission
    Recommended to use this only when submiting a form automatically


    Unfortunately, programmers (incl. HSBC) who don't know type="image"> like to do this for images: When an image is clicked,
    Form.submit() will be finally called if a form is properly validated
    BAD: NO submit event is fired. Without code analysis, difficult to know
    whether a submission has actually occurred
    2.
    AJAX Form Submission (to be discussed in the next slide)
    AJAX: Asynchronous Javascript and XML; It's all about the XMLHttpRequest
    API, study it before using it to submit form data
    3.
    18
    AJAX Form Submission (1/3)
    Demonstration:
    Email:
    Password:
    Login
    Feedback from Server:
    Nothing yet
    Advantages:
    Modern user experience
    Eliminate page-load effect, i.e. no blank screen
    Using the well-known XMLHttpRequest API
    Sends requests at background; not limited to only send form data :)
    Cancel the default form submissions
    returns false in the submit event
    19
    AJAX: Synchronous v.s. Asynchronous (1/2)
    As opposed to asynchronous calls, synchronous calls are
    blocking (hangs) until the server returns, i.e. less efficient
    Image Source: John Resig, Pro Javascript Techniques, p.26, 2007
    20
    AJAX: Synchronous v.s. Asynchronous (2/2)
    Image Source: John Resig, Pro Javascript Techniques, p.26, 2007 21
    AJAX: Implementation w/XMLHttpRequest
    // e.g to call, myLib.ajax({url:'process.php?q=hello',success:function(m){alert(m)}});
    myLib.ajax = function(opt) { opt = opt || {};
    var xhr = (window.XMLHttpRequest)
    ? new XMLHttpRequest() // IE7+, Firefox1+, Chrome1+, etc
    : new ActiveXObject("Microsoft.XMLHTTP"), // IE 6
    async = opt.async || true,
    success = opt.success || null, error = opt.error || function(){/*displayErr()*/};
    // pass three parameters, otherwise the default ones, to xhr.open()
    xhr.open(opt.method || 'GET', opt.url || '', async);
    if (opt.method == 'POST')
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // Asyhronous Call requires a callback function listening on readystatechange
    if (async)
    xhr.onreadystatechange = function(){
    if (xhr.readyState == 4) {
    var status = xhr.status;
    if ((status >= 200 && status < 300) || status == 304 || status == 1223)
    success && success.call(xhr, xhr.responseText);
    else if (status < 200 || status >= 400)
    error.call(xhr);
    }
    };
    xhr.onerror = function(){error.call(xhr)};
    // POST parameters encoded as opt.data is passed here to xhr.send()
    xhr.send(opt.data || null);
    // Synchronous Call blocks UI and returns result immediately after xhr.send()
    !async && success && success.call(xhr, xhr.responseText);
    };
    Ref: https://developer.mozilla.org/en/AJAX/Getting_Started
    22
    AJAX Form Submission (2/3)
    To generate POST parameters based on the control values
    myLib.formData = function(form) {
    // private variable for storing parameters
    this.data = [];
    for (var i = 0, j = 0, name, el, els = form.elements; el = els[i]; i++) {
    // skip those useless elements
    if (el.disabled || el.name == ''
    || ((el.type == 'radio' || el.type == 'checkbox') && !el.checked))
    continue;
    // add those useful to the data array
    this.append(el.name, el.value);
    }
    };
    // public methods of myLib.formData
    myLib.formData.prototype = {
    // output the required final POST parameters, e.g. a=1&b=2&c=3
    toString: function(){
    return this.data.join('&');
    },
    // encode the data with the built-in function encodeURIComponent
    append: function(key, val){
    this.data.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
    }
    };
    So, this can feed the data parameter for myLib.ajax({data:""})
    Note: you may refer to last week's lecture for String Concatenation
    23
    AJAX Form Submission (3/3)
    We build another reusable function submitOverAJAX()
    myLib.submitOverAJAX = function(form, opt) {
    var formData = new myLib.formData(form);
    formData.append('rnd', new Date().getTime());
    opt = opt || {};
    opt.url = opt.url || form.getAttribute('action');
    opt.method = opt.method || 'POST';
    opt.data = formData.toString();
    opt.success = opt.success || function(msg){alert(msg)};
    myLib.ajax(opt);
    };
    Finally, specify the form and a corresponding callback
    function el(A) {return document.getElementById(A)};

    var loginForm = el('loginForm');
    loginForm.onsubmit = function(){
    // submit the form over AJAX if it is properly validated
    myLib.validate(this) && myLib.submitOverAJAX(this, {success:function(msg){
    el('result').innerHTML = 'Echo from Server: $_POST = ' + msg.escapeHTML();
    }});
    // always return false to cancel the default submission
    return false;
    }
    Complicated? this final block is all you need to know (to call them) in assignment. :)24
    Our myLib.js so far...
    When all the functions (incl. myLib.validate()) are built in a single library
    (function(){
    String.prototype.escapeHTML = function(){
    return this.replace(/&/g,'&').replace(//g,'>');
    }


    var myLib = window.myLib = (window.myLib || {});

    // To generate POST parameters based on the control values
    myLib.formData = function(form) {
    // private variable for storing parameters
    this.data = [];
    for (var i = 0, j = 0, name, el, els = form.elements; el = els[i]; i++) {
    // skip those useless elements
    if (el.disabled || el.name == ''
    || ((el.type == 'radio' || el.type == 'checkbox') && !el.checked))
    continue;
    // add those useful to the data array
    this.append(el.name, el.value);
    }
    };
    // public methods of myLib.formData
    myLib.formData.prototype = {
    // output the required final POST parameters, e.g. a=1&b=2&c=3
    toString: function(){
    return this.data.join('&');
    },
    // encode the data with the built-in function encodeURIComponent
    append: function(key, val){
    this.data.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
    }
    };

    myLib.ajax = function(opt) {
    opt = opt || {};
    25
    More on XMLHttpRequest
    Reference: go to following URL if you see blank above: https://developer.mozilla.org/en/DOM
    /XMLHttpRequest/Using_XMLHttpRequest
    26
51作业君

Email:51zuoyejun

@gmail.com

添加客服微信: abby12468