Validation In JavaScript For Registration Form
Last Updated : Mar 11, 2024
IN - JavaScript | Written & Updated By - Riya
In this tutorial we will show you the solution of validation in JavaScript for registration form, here we defined registration form with input fields of ‘user id,password,username,address,country,zip code,email and gender’.
Usually we know registration form is used to store our customers details and provide some access for them. Most important thing is we need to validate because without validation we can’t collect users correct details.
Here we checked every input fields with our defined condition so we can meet our requirements.
Step By Step Guide On Validation In JavaScript For Registration Form :-
Here we need to collect users information so we defined some of input fields of ‘User id, Password, Name, Address, Country, ZIP Code, Email, Sex and Submit’.
When user submitting form ‘onsubmit’ event calls ‘fm_valid()’ function this is used to validate each inputs users entered checks whether valid or not.
If they provided input not valid it throws error message and focus on error field when user gives correct input form will successfully submitted.
<!DOCTYPE html> <html> <head> <title>Registration form validation</title> <style> h1 { margin-left: 70px;} form li { list-style: none; margin-bottom: 5px;} form ul li label{ float: left; clear: left; width: 100px; text-align: right; margin-right: 10px; font-size:18px;} form ul li input, select, span { float: left; margin-bottom: 10px;} [type="submit"] { clear: left; margin: 20px 0 0 120px; font-size:18px} </style> </head> <body onload="document.registration.userid.focus();"> <h1>Registration Form</h1> <form name='registration' onSubmit="return fm_valid();"> <ul> <li><label for="userid">User id:</label></li> <li><input type="text" name="userid" size="12" /></li> <li><label for="passid">Password:</label></li> <li><input type="password" name="passid" size="12" /></li> <li><label for="username">Name:</label></li> <li><input type="text" name="username" size="50" /></li> <li><label for="address">Address:</label></li> <li><input type="text" name="address" size="50" /></li> <li><label for="country">Country:</label></li> <li><select name="country"> <option selected="" value="Default">(Select country)</option> <option value="Id">India</option> <option value="Gm">Germany</option> <option value="Ua">USA</option> </select></li> <li><label for="zip">ZIP Code:</label></li> <li><input type="text" name="zip" size="6" /></li> <li><label for="email">Email:</label></li> <li><input type="text" name="email" size="50" /></li> <li><label id="gender">Sex:</label></li> <li><input type="radio" name="sex" id="msex" value="Male" /><span>Male</span></li> <li><input type="radio" name="sex" id="fsex" value="Female" /><span>Female</span></li> <li><input type="submit" name="submit" value="Submit" /></li> </ul> </form> <script> function fm_valid() { var uid = document.registration.userid; var passid = document.registration.passid; var uname = document.registration.username; var ucountry = document.registration.country; var uzip = document.registration.zip; var uemail = document.registration.email; var umsex = document.getElementById('msex'); var ufsex = document.getElementById('fsex'); if(userid_validation(uid,5,12)) { if(passid_validation(passid,7,12)) { if(allLetter(uname)) { if(countryselect(ucountry)) { if(allnumeric(uzip,6)) { if(ValidateEmail(uemail)) { if(validsex(umsex,ufsex)) {}}}}}}} return false; } function userid_validation(uid,mx,my) { var uid_len = uid.value.length; if (uid_len == 0 || uid_len >= my || uid_len < mx) { alert("User Id should not be empty / length be between "+mx+" to "+my); uid.focus(); return false; } return true; } function passid_validation(passid,mx,my) { var passid_len = passid.value.length; if (passid_len == 0 ||passid_len >= my || passid_len < mx) { alert("Password should not be empty / length be between "+mx+" to "+my); passid.focus(); return false; } return true; } function allLetter(uname) { var letters = /^[A-Za-z]+$/; if(uname.value.match(letters)) { return true; } else { alert('Username must have alphabet characters only'); uname.focus(); return false; }} function countryselect(ucountry) { if(ucountry.value == "Default") { alert('Select your country from the list'); ucountry.focus(); return false; } else { return true; }} function allnumeric(uzip,mx) { var l=uzip.value.length; var numbers = /^[0-9]+$/; if(uzip.value.match(numbers) && l == mx) { return true; } else { alert('ZIP code must have numeric characters only and it must 6 digits only'); uzip.focus(); return false; } } function ValidateEmail(uemail) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(uemail.value.match(mailformat)) { return true; } else { alert("You have entered an invalid email address!"); uemail.focus(); return false; }} function validsex(umsex,ufsex) { x=0; if(umsex.checked) { x++; } if(ufsex.checked) { x++; } if(x==0) { alert('Select Male/Female'); umsex.focus(); return false; } else { alert('Form Succesfully Submitted'); window.location.reload() return true; }} </script> </body> </html>
- <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
- The<html> tag is used to indicate the beginning of HTML document.
- As above shown <head> tag is contains information about webpage and external file links are declared here. <title> tag is used for set the webpage title.
- In <style> tag we defined some styles to align registration form we will see about each of them. Heading <h1> margin left aligned to ‘70px’, we defined registration form input fields and respective labels using <ul> tag so all fields look like lists.
- Generally unordered list will have bullet style so we sets ‘list-style’ value to ‘none’ and ‘margin-bottom’ to value ‘5px’.
- Then each input field labels styled by ‘float:left’ used to align all label to left side at straight direction, ‘width sets to 100px’, ‘text aligned to right side respect to width’,’margin-right sets to 10px’ and font size sets to 18px.
- The line ‘form ul li input, select, span’ refers tags of ‘input,select,span’ in form. they all styled by ‘float:left’ and margin botton sets to ‘10px’. Finally submit button styled by ‘clear: left;, margin: 20px 0 0 120px;,font-size:18px’.
- Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
- <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here and we added ‘onload’ event for loads focus on first input of ‘userid’ when we loads program on browser.
- Then form defined with ‘onsubmit’ event for loads ‘fm_valid()’ method when user submits form. Within form we defined all input fields using <ul> list tag and each input need to had attribute ‘name and id’ for validate each values.
- In <script> tag we defined fm_valid() function, here first we collects each user inputs using ‘name’ attribute value. The ‘registration’ is value of form’s ‘name’ attribute and ‘userid,passid,username,country,zip,email’ are values of respective input fields ‘name’ attribute.
- The gender value collected by using id attribute values ‘msex,fsex’. After that we used if condition with function call with respective input fields value parameters.
- So first ‘passid_validation(passid,7,12)’ function, here we collects ‘uid’ length and stored to variable ‘uid_len’ then using if condition we checks its length is equal to ‘0’ or ‘greater than 12’ or ‘less than 7’ any of these then it throws error message ‘User Id should not be empty / length be between "+mx+" to "+my’, focusing the ‘user id’ input field and returns false otherwise it returns true.
- Second if calls ‘passid_validation(passid,7,12)’ function, here we collects ‘passid’ length and stored to variable ‘passid_len’ then using if condition we checks its length is equal to ‘0’ or ‘greater than 12’ or ‘less than 7’ any of these then it throws error message ‘Password should not be empty / length be between "+mx+" to "+my’, focusing the ‘password’ input field and returns false otherwise it returns true.
- Then if calls ‘allLetter(uname)’ function, here we defined variable ‘letters’ for stores ‘/^[A-Za-z]+$/’ alphabetic pattern it will only allows alphabetic letters as input. If condition checks user enter username value ‘uname.value’ match with pattern or not if same return true otherwise it returns error message ‘Username must have alphabet characters only’, focusing ‘username’ input field by ‘uname.focus();’ and returns false.
- Next if calls ‘countryselect(ucountry)’ function, here we checks user selected value ‘ucountry.value’ with string ‘Default’ because string ‘Default’ is value for ‘Select country’ string so we can identify user not selected any other options from provided list of options. It throws error message ‘Select your country from the list’, focusing the ‘country’ field and returns false otherwise it returns true.
- Then next if calls ‘allnumeric(uzip,6)’ function, here we collects ‘uzip’ length and stored to variable ‘l’ and variable ‘numbers’ stores pattern for numbers ‘/^[0-9]+$/’ it will allow only numbers as input then using if condition we checks user entered zip code contain numbers only and its length is equal to ‘6’ or not.
- If user entered 6 digits and numeric as zip code it returns true otherwise it throws ‘ZIP code must have numeric characters only and it must 6 digits only’ error message, focusing zip code input for rewrite the mistaken input and returns false.
- In ‘ValidateEmail(uemail)’ function call we stored email pattern ‘/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/’ to variable ‘mailformat’ it allows valid email inputs only and if condition checks whether user entered email is match with pattern or not.
- If matched returns true otherwise throws ‘You have entered an invalid email address!’, focusing email input for rewrite those mistake and returns false.
- Finally ‘validsex(umsex,ufsex)’ function will called, here we checks any one option is selected or not. if selected option ‘x’ value increased by 1 otherwise x value is ‘0’ so it throws error message ‘Select Male/Female’ and focusing gender label options returns false.
- If all inputs correctly filled by user then registration form will submitted successfully and throws success message ‘Form Succesfully Submitted’, reload() method used to refresh the current page and returns true.
- For display success or error message on webpage we used alert() method it will appear at top of the window and it look like alert box. This is browser default function we can use them to display any message or value.
- Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
Conclusion :-
In conclusion we are able to know how to create registration form with validation in javascript.
When we execute our program on browser we can see the registration form, user needs to fill the form and when user submits form it collects all user entered information and stored to respective variables.
Then if condition calls each validation function for each input fields to verify each inputs and throws success message or throws what error we done by alert() method then it points which field need to rewrite.
I hope this tutorial on validation in JavaScript for registration form helps you and the steps and method mentioned above are easy to follow and implement.