2

I'm trying to implement client-side input validation for a datatables-editor that I'm rewriting. The form is created dynamically and then added to a bootstrap-modal.

I have encountered a problem where adding <pattern> and/or required doesn't result in any added functionality at all. The form just accepts the input and submits, and I'm quite confused as to why that is.

EDIT: I have added the relevant code to a plunkr

I have now added the full project. Specifically the issue is connected to the _openEditModal function and _openAddModal function, where i generate the forms dynamically and add the pattern='patternVariable'.

The pattern for this example (however it doesn't work no matter what pattern I use):

^[a-zA-Z0-9\.]+$

Creating the form:

 var data = "";

          data += "<form name='altEditor-form' role='form'>";

          for(var j = 0; j < columnDefs.length; j++){
            data += "<div class='form-group'><div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:7px;'><label for='" + columnDefs[j].title + "'>" + columnDefs[j].title + ":</label></div><div class='col-sm-9 col-md-9 col-lg-9'>";

            if(columnTypes[j].type.includes("text")){
                data += "<input type='" + columnTypes[j].type + "'  id='" + columnDefs[j].title + "'  pattern='" + columnPattern[j].pattern + "'  title='" + patternErrMsg[j].msg + "' required name='" + columnDefs[j].title + "' placeholder='" + columnDefs[j].title + "' style='overflow:hidden'  class='form-control  form-control-sm' value='" + adata.data()[0][newaData[j].name] + "'>";
            } 
            if(...){...}

            data +="</div><div style='clear:both;'></div></div>";
          }

          data += "</form>";

As you can see I add the tags like so:

pattern='" + columnPattern[j].pattern + "'  title='" + patternErrMsg[j].msg + "' required ...

The modal:

$('#altEditor-modal').on('show.bs.modal', function() {
            $('#altEditor-modal').find('.modal-title').html('Edit Record');
            $('#altEditor-modal').find('.modal-body').html(data);
            $('#altEditor-modal').find('.modal-footer').html("<button type='button' data-content='remove' class='btn btn-default' data-dismiss='modal'>Close</button>\
               <input type='submit' data-content='remove' class='btn btn-primary' id='editRowBtn'>Save Changes</input>");

I made sure that the button has type='submit' as I've read that this is what triggers the pattern-check.

editRowBtn code:

    $(document).on('click', '#editRowBtn', function(e)
    {
      e.preventDefault();
      e.stopPropagation();
      that._editRowData();
    });    

To make sure that my code is actually adding the attributes to the input i checked the console:

enter image description here

Any help or advice is greatly appreciated as I'm kinda stuck here.

BaconPancakes
  • 375
  • 7
  • 21
  • @RickBronger that whole tag is the input field, so I assumed that adding `required` anywhere in the tag would work. Is this wrong? In terms of validation I was hoping that I would be able to validate the input with `` – BaconPancakes Aug 18 '16 at 09:38
  • just set `required` on your input field wont work. Try it in a html file. you can set `class='required' ` or just call the name element in the datavalidation. like so `nameOfMyInputField: { required: true }` – Rick Bronger Aug 18 '16 at 09:45
  • @RickBronger I read the documentation here: http://www.w3schools.com/tags/att_input_required.asp and was under the assumption that the form would not be submitted if the given input-field had no input typed into it. Could you clarify? as i have no datavalidation.js file and am quite green in this area. – BaconPancakes Aug 18 '16 at 09:58
  • You are using `` but you need to use `` – Rick Bronger Aug 18 '16 at 10:54
  • @RickBronger I tried changing it to and edited my questions, but the issues persist. – BaconPancakes Aug 18 '16 at 11:39

1 Answers1

0

It's a little hard to read your examples (a plunkr would be nice :) ), but from what I can see, you've put your submit button outside your form.

That won't work, since the button won't know what it's submitting.

Try putting the submit button inside the form.

Alternatively, try using the form attribute on the submit button, which should reference the form ID. I've never used this myself, but according to MDN, it's part of the HTML5 spec.

Form attribute description from MDN:

The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place elements anywhere within a document, not just as descendants of their form elements. An input can only be associated with one form.

Community
  • 1
  • 1
Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26
  • You are right. I have put the `` in the modal footer, outside of the `
    ` which is in the modal body. However when i click the button it adds the data to my datatable, so the data is submitted, just not validated. I tried moving the button from the modal footer to inside the `
    ` but this didn't change the outcome. Also, adding the `form=formID` to the button didn't help either, so i might have to work on a different solution alltogether.
    – BaconPancakes Aug 18 '16 at 12:13
  • If you can provide a plunkr or some sorts, it'd be easier for us to help out :) – Thor Jacobsen Aug 18 '16 at 12:54
  • I have added the relevant code to a plunkr here: https://plnkr.co/edit/H39KFSYnOXplw7P9Utqt?p=preview I havent used plunkr before and haven't got more time today, so let me know if it isn't enough, and i will edit it with the whole script one of the following days. – BaconPancakes Aug 18 '16 at 14:19
  • Yea, it's not working - you've got some lib references that are missing – Thor Jacobsen Aug 19 '16 at 06:22
  • I have added the full working project to the plunkr and updated my question. Don't mind the difference in object/variable names, I just refactored some code. – BaconPancakes Aug 19 '16 at 07:55
  • Great - as fas as I can tell, it's working (ish). I don't get any browser-default validation errors (don't know if there should be any, or if that's what you're expecting), but the DOM is properly reflecting an error state. If you inspect the `validity` property of the input field, the `patternMismatch` flag will be set to true and `valid` to false, when you input an `@`. So I'd say you should read those properties manually in your javascript handler. – Thor Jacobsen Aug 19 '16 at 09:11
  • Alright, thank you, so if i would like to be unable to submit the form and display a message when `patternMismatch = true` I need to do something like: `$("formName").validity(function() { $("#inputFieldName") .require() .match("regex")` Is this correct? – BaconPancakes Aug 19 '16 at 12:21
  • Now I think you've entered the jQuery world, which is not my strong side. But yea, you'd have to read the validity of the form, and then - based on that - stop the `_editRowData` from being called – Thor Jacobsen Aug 22 '16 at 06:50
  • Thank you! it helped me a lot. However I have encountered a new problem where the `element.setCustomValidity("errormessage")` doesn't show the error-textbox even though `element.checkValidity = false;` Shouldn't it pop up automatically? – BaconPancakes Aug 22 '16 at 10:06
  • I honestly don't know - I've never interacted with the DOM validation directly. Always through frameworks, that handle that kind of "low level" API communication. But from what I can read [here](http://stackoverflow.com/questions/12785347/how-to-show-setcustomvalidity-message-tooltip-without-submit-event), you need the form to actually submit. So I'd say, removing the "preventDefault" & stopPropagation might help? – Thor Jacobsen Aug 22 '16 at 17:56