First, we will create FORM and then write code in JS on form validation and later on write code to submit the form.
CREATE A FORM :
Here, we will be designing and creating a form with Bootstrap 4(you can work with version 3 if you are comfortable with that).
First, include bootstrap in the project :
Bootstrap CSS :
jquery and Bootsrap js file :
I have included CDN of these, you can download these files from the internet and include the local file.
This is the form we are using which I used from bootstrap V4 form.
Here is the code that I got from the bootstrap website that I modified a few words.
In the above code, we have a span element for error with each input element with class name error-span and two div with class name “notification-div” one with id “error-message” and another with id “success-message“.
This is CSS to the HTML code above:
The thing we need to notice in <form> element is :
and name attribute in the input element.
This is important because we will be using FormData to send data. Form data serialize the form data in the pattern of key: value where the key is the name of the input element. If you miss the name attribute that input element value will not be attached to FormData.
Here we are using both regex and simple testing to validate input. To learn and test regular expression visit https://regex101.com/ . We have used trim to remove the boundary whitespace in the input value.
If you are not familiar with regex test function, test function returns boolean on testing pattern to the string i.e true if the pattern match in that string.
If there is any kind of validation error, we store true to the formerror variable and at last check if that variable is true. It returns false if there is an error that ends the function.
If there is no error i.e formerror is false we proceed to send the data from form to server. For this, we choose to fetch to communicate with server which is a promise-based async method.
Here, it is code to submit the form with fetch.
In line number 3, FormData() takes form element as a parameter and captures its field. It returns an object with the name property of each input element as key and their subsequent value as the value of that key.
Put this above code in the validate function after that line number 101. The code will look like this:
[codepen_embed height="619" theme_id="dark" slug_hash="KKdGYLJ" default_tab="js,result" user="pravin-poudel"]See the Pen JS AJAX fetch form submit by Pravin Poudel (@pravin-poudel) on CodePen.[/codepen_embed]
Click on JS button in the codepen above to see full view of output.
That's all for now.
Happy Learning Happy Coding.
Stay Safe and Take care of yourself and others in need.
See you again with more fun and energy. Bye !!!0