Javascript Oninvalid Pattern setCustomValidity Event Form Validations Tutorial
โœ‚๐Ÿƒ๐Ÿพโ€โ™€๏ธ๐Ÿƒ๐Ÿผโ€โ™‚๏ธ
๐Ÿ“–

Javascript Oninvalid Pattern setCustomValidity Event Form Validations Tutorial

Javascript Oninvalid Pattern setCustomValidity Event Form Validations Tutorial

In most of our mathematical educations, the odds are we wonโ€™t ever have to prove anything major mathematically, rather we just learn what has already been proved. But a lot of us envisage proving something mathematically as we trot off to school. The closest I got in my high school mathematics to proving anything was when we studied โ€œmathematical inductionโ€ for a day or two. I was pretty impressed with the idea of it, in broad brush terms โ€ฆ

Prove it for the first case.
Prove it for the next case.
Prove it for the nth case.

โ€ฆ and youโ€™ve proved it! Of course, looking back, this probably only applies to a certain subset of โ€œthingsโ€ (eg. positive integers), but I was probably off to the loo when that dampener was explained by the teacher, so Iโ€™ve come to the belief that the dogsโ€™ breakfast can be โ€œmathematically inductedโ€ โ€ฆ

Nala likes the cheese.
Luna likes the cheese.
nessie likes the cheese (and so do all the dogs whose names start with an โ€œnโ€ to my mind).

And so, onto the โ€œprove it for the first caseโ€ start yesterdayโ€™s Javascript Oninvalid Event Form Validation Pattern setCustomValidity Tutorial represented, weโ€™ve written another (this time really pared down) โ€œproofโšชof conceptโ€ liveโœ‚run calling on a โ€œseconddraftโ€ external Javascript pattern_testโšซjs you can try for yourself below โ€ฆ



Previous relevant Javascript Oninvalid Event Form Validation Pattern setCustomValidity Tutorial is shown below.

Javascript Oninvalid Event Form Validation Pattern setCustomValidity Tutorial

Javascript Oninvalid Event Form Validation Pattern setCustomValidity Tutorial

To improve on yesterdayโ€™s HTML Oninvalid Event Form Validation Pattern setCustomValidity Tutorial we immediately thought โ€œgenericizationโ€. And one approach to โ€œforce the handโ€, so to speak, regarding genericization is to โ€ฆ

  • take the original HTML (including inhouse Javascript and inhouse CSS) โ€ฆ and at least be capable of hiving off most of its code (though we just โ€˜addโ€™ today, the point being though, we could have a very minimal HTML source code footprint if we had not wanted to compare both techniques) โ€ฆ into โ€ฆ
  • new external Javascript called pattern_testโšซjs โ€ฆ called by HTML via something like โ€ฆ


    <script type='text/javascript' src='pattern_test.js?theelementid=csvlist' defer></script>


    โ€ฆ where the โ€œcsvlistโ€ is the ID of a textbox you want validated via a โ€œcomma separated positive integer listโ€ pattern (default [0-9,]*) โ€ฆworking with the parent HTML design โ€ฆ


    <form id=ejmyform method=GET data-onsubmit="return ejosb(this);" action=./pattern_test.htm>

    <input type="text" style="width:80%;" data-onblur="document.getElementById('ejfsub').click();" data-name="csvlist" id="csvlist" data-pattern="[0-9,]*" value="" data-placeholder="Please enter a comma separated positive integer list (where red dashed border flags invalid entry)" data-title="Please enter a comma separated positive integer list (where red dashed border flags invalid entry)"></input>

    <input type=submit id=ejfsub value=Validate></input></form>

To improve the โ€œgenericityโ€ aspects to this we allow for both โ€ฆ

  • a textbox in a form to have a visible submit button that sets off form oninvalid logics at that form onsubmit event โ€ฆ or โ€ฆ
  • a textbox is not in a form and the tabbing out of it with an invalid value causes CSS to show a red dashed border (as flagged to the user initially) with or without buttons of any sort

Though we do not use it in todayโ€™s โ€œseconddraftโ€ โ€œproof of conceptโ€ pattern_testโšซhtmโ€˜s liveโœ‚run, the user could specify their own pattern via a &pattern=[textboxPattern], which you can try below โ€ฆ


Previous relevant HTML Oninvalid Event Form Validation Pattern setCustomValidity Tutorial is shown below.

HTML Oninvalid Event Form Validation Pattern setCustomValidity Tutorial

HTML Oninvalid Event Form Validation Pattern setCustomValidity Tutorial

The recent HTML Oninvalid Event Form Validation Primer Tutorial taught us that โ€ฆ

  • in the client (ie. HTML and Javascript and CSS) side of the web application wooooorrrrrlllllddd it is best to involve a form โ€ฆ as much as anything to get to involve โ€ฆ
  • oninvalid event for a textbox or other user interaction HTML element โ€ฆ and today we do not involve with this โ€ฆ
    1. required attribute โ€ฆ opening the door, that way, to involving a textboxโ€™s combination of โ€ฆ
    2. pattern attribute โ€ฆ


      <input type="text" onblur="document.getElementById('fsub').click();" name="integerlist" id="integerlist" pattern="[0-9,]*" value="" placeholder="Please enter a comma separated positive integer list" title="Please enter a comma separated positive integer list"></input>

    3. setCustomValidity graphics โ€ฆ to inform of errors within an โ€ฆ
    4. oninvalid event Javascript function (set up at document.body.onload event Javascript function below) โ€ฆ


      function onl() {

      if (('' + location.hash) != '') {

      document.getElementById('integerlist').title='Regarding your invalid entry of ' + decodeURIComponent('' + location.hash).replace('#','') + ', ' + ('' + document.getElementById('integerlist').placeholder).substring(0,1).toLowerCase() + (document.getElementById('integerlist').placeholder + ' ').substring(1);

      }

      document.getElementById('integerlist').value = location.search.split('integerlist=')[1] ? decodeURIComponent(location.search.split('integerlist=')[1].split('&')[0]) : '';

      document.getElementById('integerlist').title = location.search.split('integerlist=')[1] ? ('Thanks for entering the valid "' + decodeURIComponent(location.search.split('integerlist=')[1].split('&')[0]) + '"').replace('Thanks for entering the valid ""', document.getElementById('integerlist').placeholder) : document.getElementById('integerlist').placeholder;




      document.getElementById('integerlist').oninvalid = function(event) {

      retval=event.target.value;

      if (event.target.title.indexOf(', ') != -1) {

      event.target.title=document.event.target.placeholder;

      }

      event.target.setCustomValidity('Regarding your invalid entry of "' + retval + '", ' + ('' + event.target.title).substring(0,1).toLowerCase() + (event.target.title + ' ').substring(1));

      event.target.title=('Regarding your invalid entry of "' + retval + '", ' + ('' + event.target.title).substring(0,1).toLowerCase() + (event.target.title + ' ').substring(1));

      event.target.value='';

      setTimeout(postonl, 5000);

      };


      }



      function postonl() {

      document.getElementById('integerlist').setCustomValidity('');

      }


      โ€ฆ (for that textbox) โ€ฆ
    5. fired at the form onsubmit event (at which you should return false when there is an unacceptable error in the programmerโ€™s eyes)

โ€ฆ the purpose of todayโ€™s โ€œproof of conceptโ€ pattern_testโšซhtml liveโœ‚run web application being to validate a textbox asking for โ€œa comma separated list of positive integersโ€ web application (that involves validation), and you can try below โ€ฆ


Previous relevant HTML Oninvalid Event Form Validation Primer Tutorial is shown below.

HTML Oninvalid Event Form Validation Primer Tutorial

HTML Oninvalid Event Form Validation Primer Tutorial

Itโ€™s good that there are such a variety of approaches with clientside HTML and Javascript and/or among serverside (eg. PHP, Perl, Python) components to your webpages that involve forms (because for yours truly it can seem soul destroying the way data can be in real life, asking for information off the user). You can leave it to the end of the client validation possibilities by using logic off the HTML form onsubmit event. Generally youโ€™re leaving it to the very last opportunity if you leave it to the serverside languages. But, today, at the clientside (and read more about validation off HTML Worded Validation via Client Input or Regular Expression Tutorial below if you like), weโ€™re exploring an earlier (only just) intervention than that of onsubmit, using the oninvalid event, as explained by W3schools โ€ฆ

The oninvalid event occurs when a submittable <input> element is invalid.

For example, the input field is invalid if the required attribute is set and the field is empty (the required attribute specifies that the input field must be filled out before submitting the form).

We find it suits very well those new HTML5 input element types that are trying to hone in on specific data types. To show what we are getting at here we wrote a proof of concept oninvalidโšซhtml liveโœ‚run link, for you to try some of this for yourself.


Previous relevant HTML Worded Validation via Client Input or Regular Expression Tutorial is shown below.

HTML Worded Validation via Client Input or Regular Expression Tutorial

HTML Worded Validation via Client Input or Regular Expression Tutorial

Itโ€™s not, at least for us, a trivial issue to add wording in addition to yesterdayโ€™s HTML Validation via Client Input or Regular Expression Tutorial red dashed bordering flagging invalid entries regarding โ€ฆ

  • email
  • telephone number
  • url
  • number

โ€ฆ for those two modes of validation being โ€ฆ

  • tailored HTML input type= attribute element types that came in with HTML5 โ€ฆ versus โ€ฆ
  • HTML input type=text combined via Javascript client regex matching

We wanted to add wording to ram the message home a bit better, a thought you may want to investigate yourself for mission critical information.

Would it surprise you to learn that the event driven programming code methods for the two modes above are very different? The former mode needs CSS styling :invalid selector changes that later can be detected back at Javascript (though you may want to research jQuery CSS functionalities) and though we experimented with the :after selector and the content: attribute unsuccessfully we succeeded with โ€ฆ



#iemail:invalid {

border: 2px dashed red;

max-width: calc(100% - 5px);

}



#iemail:invalid:after {

content: ' is an invalid email address';

}

โ€ฆ combined with Javascript โ€ฆ



var emailr=null;



// at document.body onload below ...

if (emailr == null) { emailr=document.getElementById('iemail').getBoundingClientRect(); }



function chkemail() {

if (iai == '') { iai=' is an invalid '; }

if (document.getElementById('iemail').value.indexOf(iai) == 0) {

document.getElementById('iemail').value=document.getElementById('iemail').value.replace(iai, document.getElementById('iemail').placeholder + iai);

} else if (('' + document.getElementById('iemail').style.border).indexOf(' dashed ') != -1) {

document.getElementById('iemail').value=document.getElementById('iemail').placeholder + iai + 'email address';

} else if (emailr != null) {

var vsemailr=document.getElementById('iemail').getBoundingClientRect();

if (vsemailr.width != emailr.width) {

document.getElementById('iemail').value=document.getElementById('iemail').placeholder + iai + 'email address';

document.getElementById('iemail').style.maxWidth=emailr.width; //'100%';

}

}
else if (emailp != '') {

document.getElementById('iemail').placeholder=emailp;

}

}

โ€ฆ as well as keyboard event logics collecting into this.placeholder the characters the user enters.

Would it surprise you to learn that the event driven programming code methods for the HTML5 input type=number within that first mode needs different validation tactics to the others within that first mode above? The reason for this is that HTML5 uses keypress limiting ideas with this input type=number type of element and we have to work โ€œaround the sidesโ€ of that (as in โ€œas well as keyboard event logics collecting into this.placeholder the characters the user entersโ€).

Central to Javascript logic here is settling on a phrase to look for, ours being โ€ is an invalid โ€ that you can see in play with thechanged email_validationโšซhtmโ€˜s liveโœ‚run link.


Previous relevant HTML Validation via Client Input or Regular Expression Tutorial is shown below.

HTML Validation via Client Input or Regular Expression Tutorial

HTML Validation via Client Input or Regular Expression Tutorial

Our attitude to validation is โ€œto get in there earlyโ€, so no matter how effective the recent PHP Form Validation via Filter Regular Expression Tutorial is with its data validation, this serverside validation canโ€™t beat client validation you do right at the โ€ฆ

  • onkeydown and onkeypress
  • onblur

โ€ฆ (optional) event logics associated with HTML input elements. With HTML5 came several input tag type= attribute validators โ€ฆ

HTML5 input tag type= attribute Client Validation Methods (can combine with pattern= attribute)
email CSS selector styling eg. <style> #iemail:invalid { border: 2px dashed red; } #iemail:valid { border: 2px solid black; } </style>
tel pattern=โ€™^[0-9-+s()]*$โ€™ and CSS selector styling eg. <style> #iipn:invalid { border: 2px dashed red; } #iipn:valid { border: 2px solid black; } </style>
url CSS selector styling eg. <style> #iurl:invalid { border: 2px dashed red; } #iurl:valid { border: 2px solid black; } </style>
number Self validates

โ€ฆ versus HTML input type=text combined with regex expression matching โ€ฆ as for telephone number โ€ฆ


function huhipn(inw) {

var isok=false;

if (inw.value != '') {

// Thanks to https://www.w3resource.com/javascript/form/phone-no-validation.php

isok=inw.value.match(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/) || inw.value.match(/^\d{10}$/) || inw.value.match(/^\d{11}$/);

if (!isok) {

inw.style.border='2px dashed red';

} else {

inw.style.border='2px solid black';

}

} else {

inw.style.border='2px solid black';

}

return isok;

}

โ€ฆ called off those aforesaid mentioned events.

You can try email_validationโšซhtmlโ€˜s liveโœ‚run link to see what we mean.


Previous relevant PHP Form Validation via Filter Regular Expression Tutorial is shown below.

PHP Form Validation via Filter Regular Expression Tutorial

PHP Form Validation via Filter Regular Expression Tutorial

With the recent PHP Form Validation via Filter Extension Tutorial we avoided โ€œthe elephant in the roomโ€ that being the use of regular expressions. No, Nala, not ๐Ÿ˜€ or even ๐Ÿคช but the definition of a date data item (or can be a PHP object) via โ€ฆ

So what is it about dates that suit regular expressions? Itโ€™s that there are so many ways to express a Date (or DateTime) in user entry land (as a โ€œtimestamp formatโ€ entry) and a regular expression set aside for some of those timestamp formats that we can think that a user may think of, could be the go to start down this road of discovery. Behind the scenes we also arrange for an equivalent PHP โ€œtimestamp formatโ€ equivalent to be sent by the HTML form controlling all this so that we can have a two phase date validation process that โ€ฆ

  • first passes the user entry through a PHP Filter extensionโ€˜s FILTER_VALIDATE_REGEXP examination, but there being no โ€œinteger rangeโ€ constraint mechanism here, you could enter a value such as โ€œ2019-02-29โ€ and it is fairly obvious what you mean with this Year-Month-Date entry, but it passes this first pass of validation (there being no โ€œinteger rangeโ€ constraint mechanism) when it shouldnโ€™t (curiously PHP date_create_from_format(string $format , โ€œ2019-02-29โ€) will return a date object that is dated โ€œ2019-03-01โ€ such is its desire to please but we do a sanity check for this โ€œempathy overshootโ€ in our code), and so we need a โ€ฆ.
  • second pass creates a PHP date object using that equivalent PHP โ€œtimestamp formatโ€ equivalent (that we separately and additionally scrutinize for that โ€œempathy overshootโ€ issue as explained above)

โ€ฆ and if successful with both passes above the user entered date information passes our validation processing to go on and win that elusive cigar?!


Previous relevant PHP Form Validation via Filter Extension Tutorial is shown below.

PHP Form Validation via Filter Extension Tutorial

PHP Form Validation via Filter Extension Tutorial

Our recent Javascript and PHP Base64 Primer Tutorial with its Base64 thoughts, the โ€ฆ



echo "<textarea id=tb64 cols=100 rows=10>" . base64_decode(urldecode($_POST['base64'])) . "</textarea><br>";

โ€ฆ of which we adopt for todayโ€™s PHP code, set our minds towards HTML form thoughts and HTML form validation thoughts. The most immediate validation thought on an HTML form is probably โ€ฆ

  • onsubmit event Javascript client logic โ€ฆ but today we go exploring โ€ฆ
  • callback PHP serverside logic via the PHP Filter extension functionalities in the pattern โ€ฆ
    $var=filter_var($prevar, );

You will see on examination of our proof of concept PHP filter_ideasโšซphp code how these PHP Filter Extensions can be used for validation purposes (with a more extensive list here), and you could try it out for yourself at this liveโœ‚run link.

If form validation interests you, perhaps a read of HTML5 Form API Validation Primer Tutorial below is in order.


Previous relevant HTML5 Form API Validation Primer Tutorial is shown below.

HTML5 Form API Validation Primer Tutorial

HTML5 Form API Validation Primer Tutorial

HTML5 is more than just the โ€œ5โ€ tagged on. Take a look at this list of API related parts to the HTML5 specification.

As you may have gleaned from our recent HTML Input Element Types Randomized History Tutorial a lot of new HTML input elements were added with the view to improving the capabilities of HTML form elements for collecting information from users interactively. Along with that, as you might expect, validation methodologies were improved, as any programmer would tell you, can be one of the most challenging โ€œpractical elementโ€ of web design to do well to not involve user error, or โ€œuser giving upโ€.

The HTML5 form API has great โ€œConstraint Validationโ€, not all new to HTML, but vastly improved and extended, as you can read a lot about at this really great webpage, thanks.

The HTML input attribute we find of great practical benefit with all this is the pattern attribute to define a constraint, in the same sort of vein as a RegEx expressions helps you perform pattern-matching and โ€œsearch and replaceโ€ functions on text. This would be great use for organizations that work with โ€œcodesโ€ or โ€œPart Numbersโ€ or SKU (stock keeping units) that follow a consistent pattern.

You can try some simple Constraint Validation at todayโ€™s liveโœ‚run link with its underlying serverside PHP code you could call html5_form_constraint_validationโšซhtml as you wish.

If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.

This entry was posted in eLearning, Event-Driven Programming, Tutorials and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *