IONIC Section 4 - 4.13 Validating User Input
Click here for more videos available on our youtube channel !Hello everyone, so with our first logic added, let's now make sure that when we click this button of confirmation, we store the title or description of the expense, the reason and the amount. So for that I will add a constant, the reason entered here, so "const enteredReason=" where I access the reason entry. Since it is an “input” element, it will have a “value” property that we can read to get the input value by the user indicating “reasonInput.value; » . We will also store the entered amount with “const enteredAmount = amountInput.value; » the same principle as for « Reason ». We can continue with these values, but it would be wise to know first, if the user has entered the correct values. For it, we can add our own simple validation logic by adding the "if" condition, if you have difficulty or if you simply want to learn the JavaScript language, I invite you to watch the videos on this technology dedicated to this learning to strengthen your knowledge. So if (enteredReason.trim().), the “trim” method allows to remove the blanks at the beginning and end of the chain. The spaces considered are the space characters as well as the characters end of line. And we will add length <= 0, if the length is then less than or equal to zero, the user has not entered anything. We will put a logical operator “or” “|| enteredAmount <=0)” indicating whether the amount is less than or equal to zero, the field is therefore not correct, and we will add another possibility “|| enteredAmount.trim().length <=0 )” when the field is simply left blank. So we have our condition here, so we'll type in a "return" to stop the execution of the function don't continue if the values are not correct. Now, if the values are correct, we want to continue our loop by indicating a console.log(enteredReason, enteredAmount); Now we come back to our page, we reload our app, we inspect the element to have an eye on our console, so I'm going to put an "invoice" expense reason, we're going to put 50.99, we validate our expense, and we see although the value of our fields are well taken into account in our console. So this is a first test, now we can try other test, like trying to validate without spending reason, when I want the input, it doesn't work, and if I enter a value of 0 and that I enter as a reason "water bill", it does not work either, however if I put a value greater than 0, 1 for example, it works very well. To make this work more, let's make sure to create Ionics elements, dynamically in the JavaScript code then to attach them to our "card" among our "input". This video is therefore coming to an end, I'll give you an appointment for the next one.