Jump to content

Stop form from clearing after validation


jonobugs

Recommended Posts

I'm making a simple contact form which works and I would like to have the user add in either their phone number OR their email. Both are fine, but at least one is required. I don't want to require both. Anyway, I created an if statement in my php code which works but when I have it return to the form, of course the form has been cleared of the user input. I then decided to create a javascript statement that does the same thing, but it clears the form as well. I personally hate it when that happens to me, so I want to make sure that whoever is filling out the form doesn't lose their information if they forget to input their phone number or email. 

I'm just learning to code, so I'm not sure what I should do to fix this problem. Is there some sort of HTML code I could use so that one of the two is required before the user hits the submit button? As I said before, I don't want to use the required function for either input. I appreciate any response! 😊

Link to comment
Share on other sites

You can do it both ways.  You can have Javascript check that and show an error message before the form even submits, and you should also check it with PHP.  With PHP, it's up to you as the programmer to fill the values back into the form if you display it again.  On the Javascript side, if you have that as a submit event handler then you need to cancel the default submit behavior if you don't want the form to submit and the page to refresh.

Link to comment
Share on other sites

The idea is to use php is to validate before processing where the form submits to itself, then on validation failure the inputs would be repopulated with values submitted to itself. Then if successful validation the repopulating of form is bypassed and processing of required data is taken place to send contact email. With JavaScript you prevent any submission until form data validates. Until the forms submission is prevented the original values remain, on-submission the values will be cleared as you are moved to contact form processing php page.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...