Would you please help me to solve? Why here has been used 'if' conditions twice? In 'Form Validation' | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Would you please help me to solve? Why here has been used 'if' conditions twice? In 'Form Validation'

<html> <form onsubmit="return validate()" method="post"> Number: <input type="text" name="num1" id="num1" /><br /> Repeat: <input type="text" name="num2" id="num2" /><br /> <input type="submit" value="Submit" /> </form> </html> function validate() { var n1 = document.getElementById('num1'); var n2 = document.getElementById('num2'); if(n1.value != '' && n2.value != '') { if(n1.value == n2.value) { return true; } } alert("The values should be equal and not blank"); return false; }

24th Dec 2022, 6:10 AM
Sony
Sony - avatar
4 Antworten
+ 1
Code you posted work, it just use single quote not double, so it don't look clear here that quote is closed. To add code please use "+" button, it will allow us to see your code in editor and test it. Code have 2 if-s, first if will check are both input have value (it is not empty), and second if check are this values same. If there are empty it will not check are they same, it will show alert with message. But if both inputs have some value it will check are this values same as return true if it is and it not it will show alert and return false. If true is returned, by default page is reloaded,and we see blank page. You can prevent reloading with event.preventDefault() placed inside validate function, and you can use this true or false to show custom error, or change style with css. In real website we collect data and send to backend to more validation and storing at database. You can collect data and log to practice frontend part.
24th Dec 2022, 10:52 AM
PanicS
PanicS - avatar
+ 1
I think you missing something in your first if condition you are trying to check null value and it should be like this n1.value!= "" Or null same for n2 and inside if body you have checked if both value will be equal then it will return true
24th Dec 2022, 6:36 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Also when form validation code return true it will try to find action attribute on form and send data to this. <form onsubmit="return validate()" method="post" action="/action_page.php" >some inputs...</form> action is attribute for form tag, it tell browser where to send data, in this case it will look for file "action_page.php". This file run on server, not on user pc, and should validate again values and send to database if valid. Thats why they return true or false in code example.
24th Dec 2022, 11:00 AM
PanicS
PanicS - avatar
0
Thank you for your reply.. although I got this from the 'form Validation' module where as like as I pasted these here what I copied from..
24th Dec 2022, 7:33 AM
Sony
Sony - avatar