The Idea
You want to ask the user to enter a name and you want to use a server-side script to confirm that the field is not left blank. If the user does not enter anything in the name field, then he should get an error message.
Implementation
Let’s start by creating an HTML file that displays a label: ‘Enter your Name’ and an input text field and a submit button. The HTML file may appear as shown below:
You can see here that the input text field is assigned class name uname for the purpose of accessing it via jQuery code. Following the input text field is an empty span element of class error. The text to this span element will be assigned from the server generated response – if the user leaves the input text field blank.
In order to specify a width to the input text field label, and a color to the error message, we need to write some style rules in the style sheet file:
.label {float: left; width: 120px; } .uname {width: 200px; } .error { color: red; padding-left: 10px; } #submit { margin-left: 125px; margin-top: 10px;}
The jQuery code to invoke the server side script is below, which passes to validateuser.php. the name entered by the user as a parameter, and displays an error message if the name is left blank by the user:
$(document).ready(function() { $('.error').hide(); $('#submit').click(function () { var name = $('.uname').val(); var data='uname='+name; $.ajax({ type:"POST", url:"validateuser.php", data:data, success:function(html) { $('.error').show(); $('.error').text(html); } }); return false; }); });
The script file validateuser.php itself, is on the server, and is meant for checking whether the name of the user is not left blank. This code looks like this:
Validating user name using a regular expression
In the above solution, the user could enter anything when they were meant to be entering their user name – including symbols. So let’s improve the server side script so we will only accept names that consist of alphanumerical and underscore only. The script file validateuser.php can be modified as shown here to achieve this for us:
SOME SAMPLE I/O AND RESULT
Input | Result/Output |
---|---|
blank | Not accepted/This field cannot be blank |
John | Accepted |
John-123 | Not accepted/Invalid User Name |
John_123 | Accepted |
No comments:
Post a Comment