<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>form validation Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/form-validation/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/form-validation/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Sat, 14 Mar 2015 17:39:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>How to do Ajax form validation with inline error messages &#8211; without using a plugin</title>
		<link>https://michaelsoriano.com/how-to-ajax-validate-forms/</link>
					<comments>https://michaelsoriano.com/how-to-ajax-validate-forms/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 14 Mar 2015 17:39:05 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4386</guid>

					<description><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before actually submitting the data to the server.<br />
<strong>Update 4/2/2016:</strong> &#8211; The code below is not meant to be a &#8220;copy and paste&#8221; type of thing. You will need some PHP and Javascript debugging experience to successfully integrate into your project.<br />
<img fetchpriority="high" decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-inline-errors.gif" alt="ajax-inline-errors" width="471" height="282" class="alignnone size-full wp-image-4387" /><br />
Plenty argue (including myself), that server side validation is more secure. This is because client side validation can be manipulated (or simply turned off). But the bad thing about server side validation &#8211; is you see the page refresh. This is considered to be <a href="http://fearlessflyer.com/10-common-ui-mistakes-and-how-to-avoid-them/">bad user experience</a> &#8211; especially in mobile.<br />
I&#8217;ve seen solutions where they use both server side and client side &#8211; with validation rules in Javascript and their server language. But that&#8217;s a bit redundant isn&#8217;t it? Plus think of the maintenance of code that you have to do. Wouldn&#8217;t it be nice to combine both?</p>
<h3>Combining both techniques</h3>
<p>What we&#8217;re trying to achieve is have the security of server side validation, the elegance of displaying the errors inline, as well as have a fall back behavior. So even when users turn off Javascript &#8211; you will see the same error messages. Oh and of course, we will also have the good user experience of the page not refreshing when there&#8217;s errors.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors2.jpg" alt="ajax-errors2" width="643" height="377" class="alignnone size-full noborder wp-image-4388" /><br />
Keep in mind that you will need a bit of programming know how &#8211; especially in PHP and Javascript. Ready to get started? Let&#8217;s begin.</p>
<h3>The Markup</h3>
<p>We start with a regular form. The submit action would be a processing page where our server side logic will take place. You can also have the processing page the same as the page where the form is. But I like to keep files separate. Copy the code below into your HTML:</p>
<pre>
<form  action="process.php" method="post">
  <label>First Name</label>
  <input name="first_name" type="text"  />
  <label>Email</label>
  <input name="email" type="text"  />
  <input type="submit" value="Submit" />
</form>
</pre>
<p>Nothing fancy here. Just a regular form and a couple of fields. Remember to make your field names unique &#8211; for this is what we&#8217;ll use to validate our form.</p>
<h3>The Processing Page</h3>
<p>So when our form submits, it passes the $_POST array to this page. If you&#8217;re new to validating forms, the code below simply goes through the array and checks it against our rules for each field. Note that in our case &#8211; I&#8217;m simply checking if first name and email is empty. Of course in the real world, you will have to check for valid email and such.</p>
<pre>
session_start();
if(isset($_POST)){
  	if (empty($_POST['first_name'])) {
		$_SESSION['errors'][‘first_name'] = ‘First name is missing’;
        	}
	if (empty($_POST[‘email’])) {
		$_SESSION['errors'][‘email'] = ‘email is missing’;
        	}
        if(count($_SESSION['errors']) > 0){
	    //This is for ajax requests:
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                echo json_encode($_SESSION['errors']);
                exit;
             }
	    //This is when Javascript is turned off:
           echo “<ul>”;
           foreach($_SESSION['errors'] as $key => $value){
	      echo “<li>” . $value . “</li>”;
           }
           echo “</ul>”;exit;
    }else{
	//form validation successful - process data here!!!!
   }
}
</pre>
<p>The key to the code above is the check for an Ajax request. Notice the json_encode() method. This is when it&#8217;s an Ajax request and we simply echo our error array in JSON format. We will need this to format our inline messages later. The rest of the code is simply handled as if it&#8217;s regular server side processing.<br />
Again, notice the part where if it&#8217;s NOT an Ajax request &#8211; we simply echo out a list of our validation errors. You would probably want to style this better, or even echo it out in the same page as the form. But for the sake of our tutorial, I want to make it short and concise.</p>
<h3>Our Javascript</h3>
<p>I prefer to write jQuery, so the code below will only work if jQuery is included. The code below is to be added to our form page:</p>
<pre>
var data = {};
$(document).ready(function() {
  $('input[type="submit"]').on('click', function() {
      resetErrors();
      var url = 'process.php';
      $.each($('form input, form select'), function(i, v) {
          if (v.type !== 'submit') {
              data[v.name] = v.value;
          }
      }); //end each
      $.ajax({
          dataType: 'json',
          type: 'POST',
          url: url,
          data: data,
          success: function(resp) {
              if (resp === true) {
                  	//successful validation
                      $('form').submit();
                  	return false;
              } else {
                  $.each(resp, function(i, v) {
	        console.log(i + " => " + v); // view in console for error messages
                      var msg = '<label class="error" for="'+i+'">'+v+'</label>';
                      $('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
                  });
                  var keys = Object.keys(resp);
                  $('input[name="'+keys[0]+'"]').focus();
              }
              return false;
          },
          error: function() {
              console.log('there was a problem checking the fields');
          }
      });
      return false;
  });
});
function resetErrors() {
    $('form input, form select').removeClass('inputTxtError');
    $('label.error').remove();
}
</pre>
<p>Plenty of things going on above. Of course everything is wrapped inside our document.ready() handler, then we put a .click() for our submit button. So every time we click the submit button, we go through each field in the form and create a data object. This object contains the field names and their respective values (you can also use jQuery&#8217;s .serialize() for this purpose).<br />
We make an Ajax call to our processing page &#8211; where it does the validation in our PHP code previously. Now, remember our server side will echo a JSON object with our field names and error messages? We simply handle this by adding an error class and adding a &#8220;label&#8221; with the message through jQuery&#8217;s .after() function.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors4.jpg" alt="ajax-errors4" width="746" height="327" class="alignnone size-full wp-image-4390" /><br />
Of course, if there&#8217;s no errors &#8211; the form does a hard .submit() &#8211; to the same processing page and handled accordingly.</p>
<h3>Our CSS</h3>
<p>Of course, we have add our styling so our field will look like our screenshots above. Simply add this code inside style tags.</p>
<pre>
.error {
   color: #ff0000;
   font-size: 12px;
   margin-top: 5px;
   margin-bottom: 0;
}
.inputTxtError {
   border: 1px solid #ff0000;
   color: #0e0e0e;
}
</pre>
<p>Again, the styles are real basic and you probably want to do better in your own forms.</p>
<h3>Conclusion</h3>
<p>So there you have it. We&#8217;ve combined best of both worlds: server side and client side validation in one solution (thanks to Ajax). Our code has clear separation and very manageable. If a field validation rule has to change &#8211; we only need to change it in one place: the server code. Also, our users will benefit from our friendly form &#8211; and the way it gracefully tells them when they&#8217;ve missed a field and such.<br />
Let me know your thoughts and if you think this solution is a good fit for your projects. </p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-ajax-validate-forms/feed/</wfw:commentRss>
			<slash:comments>40</slash:comments>
		
		
			</item>
	</channel>
</rss>
