begonavizcaino / ee417-groupD

0 stars 0 forks source link

Javascript #6

Open EtienneDx opened 3 years ago

EtienneDx commented 3 years ago
EtienneDx commented 3 years ago

Here's a snapshot of what I used in my assignment3 for form validation, which got me a very good grade. If you feel like it, maybe we can do something simillar?

$(function() {
    $('#sign-up').submit(function (e) {
        var $form = $(this);
        var valid = true;
        // .each is synchronous, so no problem modifying valid inside of it
        $form.find(".input-group.required").each(function() {
            valid = checkGroup($(this)) && valid;// check all groups
        });
        if(!valid) {
            e.preventDefault();
            //submitForm($form);// submit only valid forms
        }
    });

    $('.form .input-group.required').on('change', function() { checkGroup($(this)); });// when a group change, check it

    $('.view-results').click(displayResults);
});

function checkGroup($grp) {
    var valid = true;
    var $input = $grp.find("input");
    if(typeof $input.val() !== "string" || $input.val().length == 0) {
        var $ifReq = $grp.find(".if-required");
        if($ifReq.length == 0) {
            $ifReq = $('<span class="if-required">This field is required!</span>').appendTo($grp);// add comment on empty required groups
            valid = false;
        }
    } else {
        $grp.find(".if-required").remove();// not empty, we can remove the required span
    }
    var match = $grp.data("match");
    var evaluate = $grp.data("eval");
    if(typeof match === "string") {// there is a data match attribute
        const b = $input.val().match(match) != null;// we check wether it matches
        $grp.toggleClass("valid", b);
        $grp.toggleClass("not-valid", !b);
        valid = valid && b;
    } else if(typeof evaluate === "string") {// no data match but data eval
          const b = valid && eval(`(function(value) {
              return ` + evaluate + `
          })`)($input.val());// we create a function to check the validity
          $grp.toggleClass("valid", b);
          $grp.toggleClass("not-valid", !b);
          valid = valid && b;
    } else {// no data attribute, we simply set the classes
        $grp.toggleClass("valid", valid);
        $grp.toggleClass("not-valid", !valid);
    }
    return valid;
}

It's to be used in conjunction with:

<div class="input-group required" data-match="[a-zA-Z-]+">
    <label for="fname">First name</label>
    <input type="text" name="fname" id="fname" />
    <span class="if-valid">All good!</span>
    <span class="if-not-valid">Your first name is not valid!</span>
</div>

Not necessarily the best solution, but I think it works rather well and behaves in a nice manner