JS Coding Questions Logo
JS Coding Questions
#273💼 Interview💻 Code

How do you perform form validation using javascript

Advertisement

728x90

JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted.

Lets' perform user login in an html form,

html
1<form name="myForm" onsubmit="return validateForm()" method="post">
2  User name:
3  <input type="text" name="uname" />
4  <input type="submit" value="Submit" />
5  </form>

And the validation on user login is below,

javascript
1function validateForm() {
2  var x = document.forms["myForm"]["uname"].value;
3  if (x == "") {
4  alert("The username shouldn't be empty");
5  return false;
6  }
7  }

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 16

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
273of476