13. JS Forms Öffentlich

13. JS Forms

Kostas Diakogiannis
Kurs von Kostas Diakogiannis, aktualisiert more than 1 year ago Beitragende

Beschreibung

Working with forms in Html5 and JS

Modulinformationen

Keine Merkmale angegeben

Kontext

Course's Objectives 1. To understand how HTML5 forms work. 2. To learn the different types of events a form can have. 3. To learn the different HTML input's attributes. How to use them for validating data. 4. What is the invalid event on Input fields, when it is triggered and what to do with it. 5. How to check the validity of an input field and how to identify the invalid property. 6. How to display custom error messages on different invalid attributes. 7. How to style differently invalid fields from CSS pseudo-classes. 8. The pattern keyword and how can we use regular expressions to search for a pattern.
Weniger sehen
Keine Merkmale angegeben

Kontext

JS Form Validation As you have probably guessed, not all data that comes or stems from an HTML form should be accepted. Sometimes we want to accept data from the user that matches specific criteria. That means that most of the time the data that comes from a form should be validated before submitted. Normally a validation of a form happens on every input field on the submit event. But also can be specified otherwise as we will see later.
Weniger sehen
Keine Merkmale angegeben

Kontext

The Form events The Form element can have many events attached, but for now we are going to focus to the two main ones. The submit event and the reset event. The Submit event. This is the final action a form takes, and the purpose of the form itself. To submit, or send the data that the form is comprised of to a specific destination.This destination will grab the data and will do something with it. The default behavior after the sending of data, is to reset the form and reload the page. The 'How' and the 'Where' are two questions that will be answered later. The Reset event. This action can be taken any time before submit and restores the data of each input field of a form to it's initial state. It doesn't submit, it just starts over. Reset can be heavily used on a click of a button in order to clear all the fields of the form from any data before submitting. After submitting all the fields are cleared, which is a part of the form's submit event's default behavior.
Weniger sehen
Keine Merkmale angegeben

Kontext

Form validation attributes 99% of the times we want to validate each input field separately. This make sense because not all the inputs of a form are the same. Thus, we validate differently based on the type of the information, we are asking from the user to fill in. Validating through every input is possible by adding to this input specific attribute keywords with corresponding values to the HTML elements. Some of these attributes are shown above, and they can vary depending on what do we ask from this field. We can specify that this field should be required, so that the user cannot ignore it, or define a range of accepted values (for example age more than 18), combinations are also possible and many many more. Bear in mind, that not all attributes are destined to work with all types of inputs. Some are bound to specific input.  In the end we can apply also an attribute to the form element itself, This is the novalidate attribute. By default a form will validate every input to check if the data is valid or not before submitting. Unless we put the novalidate attribute to the form element. Then regardless of what validate keyword every input has, the form will not be validated at all and we accept everything. If you want to check all the input attributes of a form, do it here.
Weniger sehen
Keine Merkmale angegeben

Kontext

Create a simple validated form Get yourself familiar with validating forms. For your next task you should create a form within your HTML with the following fields and validates respectively: 1. Create a text input type field, for storing the name of the user. This should accept only strings between 4 and 20 characters.  You may find useful the minLength and maxLength attributes here. 2. Create an input field of type password, to store the password of the user. This should be visually hashed (non-visible, only dots) and it should be at least 8 characters long. 3. Create an input field of type email, you don't have to do anything here. Validation comes automatically in case the user types something that doesn't seem like a valid email address. 4. Last put an input field of type number, that prompts the user to put it's age. The value of this field should be at least 18 and at most 70. May you want to find more about the min and max attributes here. All fields should be required. That means they can't be omitted. Try to submit the form, by putting at least one of the criteria wrong intentionally. What can you see? Which error comes first? Where does this error message come from?
Weniger sehen
Keine Merkmale angegeben

Kontext

Check Validity Validating input fields is possible but it doesn't come from a black sorcery.  It is possible through a specific JS function that every input DOM element has. The checkValidity() function. This functions checks for all the criteria an input field contains and returns a boolean value (true if the data is valid, false if not).  Anytime this function returns a false value, triggers the 'invalid' event on the field. Let's see an example of this.
Weniger sehen
Keine Merkmale angegeben

Kontext

The invalid event The invalid event is a unique event to html DOM form input fields. It is triggered any time the checkValidity() functions returns a false boolean value (see a slide below). Inside this event we can specify and define a set of actions that are going to happen any time a field contains an invalid data.  Thus we can use the setCustomValidity() function to create a custom useful error message to the user and avoid giving him the standard default message from browser (preventDefault() is necessary to avoid this before doing anything further).
Weniger sehen
Keine Merkmale angegeben

Kontext

Different validity errors Every input element has a specific object that is called validity. This object has all the information about which part of the data has gone wrong and against our validation restrictions.  Some of the fields are very descriptive and they are correlated with the conditions we have set. All these properties that are inside the validity object of each element return a boolean and indicate the root of a problem. If all of them are false finally, the valid property returns true and the input's data is considered valid.
Weniger sehen
Keine Merkmale angegeben

Kontext

Showing Custom error messages Every browser has a default behavior that is executed on an invalid event. This default behavior contains all the necessary steps, from triggering the invalid event, detect the specific attribute that produces the error through the ev.currentTarget.validity.property and returns a predefined message inside a predefine box.  If you don't want this to happen, and you want to return your own custom message and implement your custom functionality, you can apply preventDefault on the invalid event at the beginning.  Then it is necessary to apply under each error a specific message. We do this by using the setCustomValidity() function, and inside we pass the string, which we are going to show to the user as a message. For further submissions, and after that we set the setCustomValidity('') to an empty string. That means that after we have displayed the error, we don't block from submitting any further. The empty string specifies that there was an error for this attempt of submit. If we don't change then the block of submit continues!!!
Weniger sehen
Keine Merkmale angegeben

Kontext

CSS Form pseudo selectors CSS pseudo selector forms exist in order to style differently form elements that are currently under a specific condition or they hold a specific attribute.  For example you can give more  emphasis to the required fields or mark red the ones that are currently not valid. etc. The syntax is the same as with any CSS pseudo selector and the list can be found above.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-1 Custom validation of the CV application Revisit and refactor the DOM-9.cv application by adding validation to the form before submitting it. The requirements of the exercise are: 1. Give the user the chance to reset his CV any time he wants by adding a second button of reset type next to submit button. 2. The first input (of type text, regarding the name) should be a required input. Any time the user releases a key on his keyboard, the field should be validated, and if it is empty, then a custom error message should be put into the paragraph below the input field, with a text of 'Were you born without a name?'. This happens on 'invalid' event of the field, don't forget to prevent the default behavior before doing anything else, and to restore the customValidity of the field back to an empty string. 3. Regarding the date of birth input, the user must have been born before the 14 November 2000. So we are sure that he is already an adult (feel free to change this date to your current date). If the user has been born after, the custom error message should appear on the paragraph below the input field 'Go and drink your milk kiddy'. This field should be validated anytime we have value change. 4. Last but not least, the textarea should be of 140 characters long (twitter style). The validation should happen again on keyup and the user should be always aware about how many characters have left for his message.   Hint: Use the invalid pseudo selectors in css to hide or show the paragraphs that will hold the custom error messages.   All in all the final result should like this Note: The image may not appear because the app is hosted through netlify. But it should appear on your local server in your PC.
Weniger sehen
Keine Merkmale angegeben

Kontext

Text Validation Sometimes when dealing with text input fields, validating only the length of the string or if it is there or not is simply not enough. Most of the times we want to ensure that the user is giving us a data on a specific predefined format. That way we can define a pattern of the expected string.  This pattern is only an abstracted blueprint of how the data from the user should be like in order to be accepted.  Think a bit about the e-mail validation forms. There are many email type accounts. Let's look at some of them as examples:  kostasdiakogiannis23@gmail.com johndoe@hotmail.com freddy.kruger@gmx.net Now although at a first glance these emails seem to be completely different, if you look closely you may find that all of them are comprised from some parts. The first part that can contain possibly letters, numbers and/or special characters, that is always followed by a literal '@', then the second part which is also comprised of a unknown number of letters, numbers and special characters and ends with a literal dot (.) followed by the address (which is comprised by letters and most of the times the length is between two and four). In order to accept multiple addresses, that match all these different combinations you should write hundreds of lines of code to predict all the outcomes.
Weniger sehen
Keine Merkmale angegeben

Kontext

Regular Expressions Hopefully there is a solution to that! Instead of trying to validate strings in different combinations and character by characters we can achieve everything in one line! How? Regular Expressions come to the rescue!  Regular expressions are a compact way to define in one line an abstract layout of how an accepted string (or value that comes from data) should look like. Be careful! Regular expressions (or RegEx as they are called for economy), are no subject to JavaScript as language. They are only a way to define patterns and they work well with many other languages as well (python, ruby etc). Let's leave aside the 'how' and focus a bit on 'why'. Especially what is the problem they solve?
Weniger sehen
Keine Merkmale angegeben

Kontext

The telephone number problem Think a bit three cellphone numbers that come from Germany in the class. Gather them and write them on the whiteboard.  Do you observe similarities between the numbers? If yes, which?  Identify the pattern first verbally, and then we can see how we can get a match for all. Elaborate on that.
Weniger sehen
Keine Merkmale angegeben

Kontext

Define patterns Inside the slashes we can freely define our pattern. If you type a series of characters these characters will be taken as a literal, and the only match that you will accept is what you have inside the slashes.    We can test if we have a matching pattern or not with the test function that is being executed on a regex and accepts the string, that our regex will be tested on. This function returns a boolean. In this case line 7 will return a true value. If you want to practice more, check this site here!
Weniger sehen
Keine Merkmale angegeben

Kontext

Alternatives and Optionals We can have alternative options with the vertical slash | operator. That means that both values will be accepted. Either the first or the second option in this case, but both as literals. There is no limitation on alternatives, this can go on as long as you want by adding more and more alternatives.
Weniger sehen
Keine Merkmale angegeben

Kontext

Alternatives and optionals With a ? question mark, we can specify that a part of the string is optional and could be additionally accepted if there, but not mandatory.  The main difference between optionals and alternatives is that optionals mean, that either this character will be put or nothing, alternatives in contrast mean either the one, or the other one. But in the end for sure something. Nothing is not an option. If we don't want to have partial match we can specify that the string that we are testing on should should begin and end with the pattern we have, and it is not a subset of a bigger string. To specify that this is the beginning we do it with the ^ character, and the end with a $ dollar sign character.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-2 The Mohammed's Name Problem Write a single regular expression that accepts these variations of Mohammed's name: 1. Mohammed 2. Mohamad 3. Muhammad 4.Mohamed Any other version of the name or any other string will be rejected! Hint: You may want to refresh the alternatives and optional characters knowledge you gained.
Weniger sehen
Keine Merkmale angegeben

Kontext

Metacharacters Metacharacters in regular expressions are called all these weird special characters to regex that mean something specifically to a pattern and cannot be taken as a letter literal.  We place them always between the two backslashes where we define the body of our pattern. Some of the most common used include:  \w Which matches any letter or number. It is called word character \d which matches all digits(numbers) \s matches a space character \. matches all letters, digits and special characters (be careful with that!) \D all non-digit characters \W matches all non-word characters (everything that is not a letter nor digit)   And many many more, you can find the full list here!
Weniger sehen
Keine Merkmale angegeben

Kontext

Working with character sets A character set, sets available all the possible characters that could be potentially used for a specific character in a pattern. That being said you can specify that you accept one character in your pattern to hold letters between E and K. You can do that by typing [E-K]. Same applies to numbers also as you can see with the picture above.  Characters sets can also be combined. For example: [0-5P-Q] => this matches a characters if it is a number between 0 and 5 (both included), or a letter between P and Q. Bear in mind that a character set represents only one character in your pattern! If you want this pattern to expand to many characters read further!
Weniger sehen
Keine Merkmale angegeben

Kontext

Quantifiers  Quantifiers are used when we don't know exactly from how many characters our pattern is comprised of. For example we want to accept names from an input html field. That means that we should accept all possible letters from A to Z.  We could use a character set in this case like [A-Z], but this is only for one character. We would like to repeat this process for all characters of a string.  In case you know the exact number of letters you want your pattern to match you can use the curly braces as quantifier to have something like /^[a-z]{10}$/i. This matches a string that is comprised exclusively from 10 letters.  With the + quantifier you can use the same pattern for any amount of repetitions if you don't care about the exact length of the data that you are going to accept. ex: /^[a-z]+$/i Other regex quantifiers for defining the minimum or the maximum amount of a character that is allowed can be found above.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-3 Accept a full name with spaces Write a single regular expression that accepts a full name pattern with minimum 3 letter characters and maximum 30 of them. In between the characters the user can have many spaces also. No numbers and no special characters are accepted. Letters can be either lower case or upper case. Data that should be accepted: 1. Kostas Diakogiannis 2. Daniel Cipolla 3. Mauricio Cifuentes Navarro But not! Daniel23, Kost@s etc
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-4 Accept a password pattern Create a simple regular expression pattern for validating a password from the user. The user can have letters, numbers and special characters but no spaces are allowed. Additionally the password cannot be less than 8 characters and more than 20 characters.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-5 Validate a German cellphone number Validate if a cellphone number has the typical German number structure. The number should start with 0049, if not it should start with 0. After that, an optional space could follow, and then 11 digits from 0 to 9. In between these 11 digits the user has the opportunity to put an optional space wherever he wants. Accepted data:  1. 0049 15770452536 2. 015770452536 3. 00491577 0452536 4. 0157 74 525 36 Hint: Check the grouping () characters expression again. Try not to write 11 times the same pattern for every character. What if we are talking about 50 or 500 characters?
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-6 Validate an email address Write a single regular expression that validates an email address from the user. The rules are: The first part until the @ sign can contain any character, letter, digit. Special characters like the ., the $ or the  # are also accepted but only those. This part should contain at least 2 and max 50 characters. Then follows the literal @, after this, we accept a minimum of 4 and maximum of 50 letter characters.  Then follows the literal .  Then for now we accept only addresses that match either com, net or org. For example the email address: kostas.diakogianni$23@gmail.com is accepted and valid. But not the: kostas.diakogi@nnis23@gmail.com is not!
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-7 Check valid url address Check if a url address is valid. Create a single regular expressions with all the rules you have learned in order to accept data into following format. 1.http://www.lettersornumbershere.extensionhere 2.https://wwww.againnumbersorletters.extensionhere The rules are simple, the first part must be literally either http or https.  Follows literally the '://www.' part. This is like a constant. It must be there exactly as it is. After the literal dot follows an unknown series (lets put it between 2 and 50) characters that could be either letters or digits, followed by a literal dot . at the end of it. After the dot, follows the last part which could contain only letters (min 2 and max 4 characters).
Weniger sehen
Keine Merkmale angegeben

Kontext

The boundary metacharacter Take a close look to the string in the picture above and the regular expression pattern that we have defined below. Normally, and if you ignore this weird \b thing, that we have currently no idea of for now, you should expect that this log returns true, because the 'cat' string is included as a part of the string in the 'catwoman' word. Thus we get a partial match, which evaluates into a match.  This is a very rational thought, since there is no ^ caret sign before, and  no $ dollar sign after. But this \b kinda acts like so, but not  totally. What is it then? The boundary metacharacter matches only the cat (which is between the metacharacters) only if the word is completely on it's own and no part of another one (catwoman in this case). The first \b means that there is nothing before cat in the same word, which is true, the problem is the second \b in the pattern, because that means that there should be also nothing after the 't'. The only acceptable thing would be either a space or the end of the string.  Another example would be if we had the string 'I am the luckiest person in the world!'. And the regex is /\bluck\b/i. In this case this evaluates to false. Bear in mind though:  /\bluck/i evaluates also to true.  But : /luck\b/i  evaluates to false.  \b means that nothing should be either before or after or both in the same word.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-8 Who loves bears? Time to prove that you love also bears!  Create a simple regular expression pattern that matches if a string (it could be a whole sentence or just one word) contains the word 'bear' inside (ignore case sensitivity). So the regex should accept: 1. bear 2. I love watching bears fishing salmons in Kamtschaka. But not! 1. My morning routine is to shave my beard. 2. The heat is unbearable!
Weniger sehen
Keine Merkmale angegeben

Kontext

The Match function The match function is another function, after the test function, that is very useful when working with regular expressions and testing strings. There are two main differences than test. 1. The match function takes place on the tested string, and accepts the regex expression as an argument inside the function. 2. The match does not return a boolean like the test function, but an array of all the matches that have been found (in case of g modifier is active, otherwise only the first match). When we say matches, we mean the string itself. This is very useful when we are trying to find out how many matches of the specified pattern we found in the tested string (the length of the array that comes back in this case).
Weniger sehen
Keine Merkmale angegeben

Kontext

Modifiers Modifiers are placed outside the two backslashes on the right side and they modify the method of the pattern, but not the pattern itself. The first modifier is the i modifier. When present, ignores the case sensitivity between the pattern and the tested string. So returns a match regardless of uppercase or lowercase issues. The g modifier, or global modifier, does not return only the first match that the pattern identifies but continues throughout the whole string for further matches. This is extremely useful when used alongside the match function for type of string. Last there is the m modifier, that checks also for multi-line strings and doesn't stop in the end of the first line only.
Weniger sehen
Keine Merkmale angegeben

Kontext

FO-9 Facebook vs Twitter Create a textarea so the user can type some things about the social media he uses everyday.  Try to capture how many times the user has written the word 'facebook' and how many times the word 'twitter'. Create two counter variables for both and next to the textarea have 2 span elements, one for each saying: FB: 5 Shares (assuming that the word 'facebook' was found 5 times in the text) TW: 4 Tweets (assuming that the word 'twitter' was found 4 times in the text). Ignore case sensitivity. Bonus: Make this work even if the user types at some 'fb' (facebook counter gets one more in this case) or 'tw' (twitter counter increases). At the end your result should look something like this:
Weniger sehen
Keine Merkmale angegeben

Kontext

The pattern attribute The pattern attribute is unique to input elements and especially to those of type text. Inside you can write your regular expression pattern.  Bear in mind that the / / backslashes are not accepted and not used since there is no way to add modifiers. There is no official way to ignore case sensitivity, check for global matches or multiline results. Thus it would be really recommended not to be used heavily, except for easy patterns, and for most of the cases, it is recommended  JS should be used as an alternative for pattern.
Weniger sehen
Keine Merkmale angegeben

Kontext

Form Attributes The form has attributes on it's own, not only the input fields that is comprised of. Some of them we have already seen them, like the novalidate attribute, some of them not. Two of the most important ones are the action attribute and the method attribute.  The action attribute defines the responsible file for accepting the data from the client. Normally this is a server-side script that does something with it, either saves the data to database, retrieve it from there, serves a new html file to the client and many many more. The file's address is used with a relative path here. What is going to happen after the file (server's API) has received the data is no subject to client side programming, and it shouldn't bother us for now.  The method attribute is descriptive. Defines the way that the data is going to be sent to the server. There are mainly 5 http methods: 1. Get - Mostly used for fetching data from an external source 2. Post - Mostly used for sending data to a remote source 3. Put - Used for update data to a remote source 4. Delete - Delete data to a source 5. Patch - Similar to put, used for updating but instead of a whole object, only a piece of it. We will learn more about the possible methods and what do they mean when we use the fetch api to talk with servers and exchange data. Until then, bear in mind, that when dealing and exchanging sensitive data (credit card numbers, bank accounts, user password etc) always use post instead of get. Get request includes the body of the request to the url, while post doesn't.
Weniger sehen
Zusammenfassung anzeigen Zusammenfassung ausblenden