Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts

Collection of Form Validation

checkEmail()

Next we want to see if the email address the user entered is real. The most effective way to do this is to go out on the Net and ask the domain the user claims to hail from if that the person actually has an account. But this takes a big toll on the machine that’s running the checks — and it isn’t possible with JavaScript anyway. With JavaScript we can check to see if the email string looks like an email address. We want it to follow this format: some characters, then an at symbol (@), then some more characters, then a dot (.), then two or three more characters, and that’s it. This won’t be perfect validation —it is possible to slip phony non-RFC-compliant addresses by it — but it’s normally good enough. If the pattern doesn’t match, we reject the email address.

The regular expression that expresses the format goes something like this: /^.+@.+\..{2,3}$/. The carat (^) means the start of the string and the dollar sign ($) means the end of the string. By surrounding the rest of the regular expression with these characters, we ensure that we evaluate the entire string, rather than just a portion. Each .+ means "at least one character" — the dot (.) means "any character"” and the plus sign (+), you recall, means "one or more." The .{2,3} portion means "two or three characters." And when we want to match a literal dot, we need to escape the character with a backslash. That’s why we have \. there.

var emailFilter=/^.+@.+\..{2,3,4,6}$/;
if (!(emailFilter.test(strng))) {
error = "Please enter a valid email address.\n";
}

Again, we want to check to make sure that no forbidden characters have slipped in. For email addresses, we’re forbidding the following: ( ) < > [ ] , ; : \ / "

var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
if (strng.match(illegalChars)) {
error = "The email address contains illegal characters.\n";
}
checkPhone()

To validate a phone number, first we want to clear out any spacer characters, such as parentheses, dashes, spaces, and dots. We can do this with a regular expression and the replace() method, replacing anything that matches our regular expression with a null string. Having done that, we look at what we have left with the isNaN() function (which checks to see if a given input is Not A Number), to test if it's an integer or not. If it contains anything other than digits, we reject it.

var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
//strip out acceptable non-numeric characters
if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.";
}

Then we count the length of the number. It should have exactly ten digits — any more or less, and we reject it.

if (!(stripped.length == 10)) {
error = "The phone number is the wrong length.
Make sure you included an area code.\n";
}

check Dropdown()

Finally, we want to make sure that the user has selected an option from our drop-down menu (and not the first option, which isn’t an option at all, but just a "Choose one" header). For this, we use the select object’s selectedIndex property, which returns the index of the selected option. If the index is 0, we reject the input.

function checkDropdown(choice) {
var error = "";
if (choice == 0) {
error = "You didn't choose an option
from the drop-down list.\n";
}
return error;
}
checkRadio()

To make sure that a radio button has been chosen from a selection, we run through the array of radio buttons and count the number that have been checked. Rather than sending the whole radio object to a subfunction, which can be problematic (because the radio object has no property indicating which value has been chosen), we pre-process the radio form element in a for loop and send that result to a subfunction for evaluation.

for (i=0, n=theForm.radios.length; i<n; i++) {
if (theForm.radios[i].checked) {
var checkvalue = theForm.radios[i].value;
break;
}
}
why += checkRadio(checkvalue);

function checkRadio(checkvalue) {
var error = "";
if (!(checkvalue)) {
error = "Please check a radio button.\n";
}
return error;
}

checkWholeForm()

A master function, called checkWholeForm() is placed at the top of the page that contains a form.

function checkWholeForm(theForm) {
var why = "";
why += checkEmail(theForm.email.value);
why += checkPhone(theForm.phone.value);
why += checkPassword(theForm.password.value);
why += checkUsername(theForm.username.value);
why += isEmpty(theForm.notempty.value);
why += isDifferent(theForm.different.value);
for (i=0, n=theForm.radios.length; i<n; i++) {
if (theForm.radios[i].checked) {
var checkvalue = theForm.radios[i].value;
break;
}
}
why += checkRadio(checkvalue);
why += checkDropdown(theForm.choose.selectedIndex);
if (why != "") {
alert(why);
return false;
}
return true;
}

If you have better solution, just tell me !

Chroma Hash: Interesting visualization of your password

Matt Thompson has created a fun little jQuery plugin called Chroma-Hash that "dynamically visualizes secure text-field values using ambient color bars":
Password entry can be frustrating, especially with long or difficult passwords. On a webpage, secure fields obscure your input with •'s, so others can't read it. Unfortunately, neither can you—you can't tell if you got your password right until you click "Log In".

Here is a snippet of the magic:


  1. $(this).css({position: 'absolute',
  2. left: position.left + width - 2,
  3. top: position.top,
  4. height: height + "px",
  5. width: 8 + "px",
  6. margin: 5 + "px",
  7. marginLeft: -8 * (i + 1) + "px"
  8. }
  9. );
  10. });
  11. var id = $(this).attr('id');
  12. var md5 = hex_md5($(this).val());
  13. var colors = md5.match(/([\dABCDEF]{6})/ig);
  14. $(".chroma-hash").stop();
  15. chromaHashesForElement(this).each(function(i) {
  16. $(this).animate({backgroundColor:"#" +
  17. colors[i]});
  18. });

If you have better solution, just tell me !

E-mail Validation With Javascript

The function below checks if the content has the general syntax of an email.

This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign:



function validate_email(field,alerttxt)
{
with (field)
{
apos = value.indexOf("@");
dotpos = value.lastIndexOf(".");
if (apos<1dotpos - apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}

The entire script, with the HTML form could look something like this:


<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{email.focus();return false;}
}
}
</script>
</head>
<body>
<form action="submit.htm"
onsubmit="return validate_form(this);"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>

If you have better solution, just tell me !

Form Validation using jQuery

Let us start with a simple example. Our demonstration form contains four fields: name, e-mail, comment and URL. As you can see, the first three fields are required, whereas the URL field is optional. If you submit the form without filling in the required fields, you will be prompted with an error message.
Here is the code we used for the form in the demonstration above.


<html>
<head>
<title>Simple Form Validation</title>
<script type="text/javascript" src="http://code.jquery.com/

jquery-latest.js"></script><script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/

validate/jquery.validate.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required",// simple rule, converted to {required:true}
email: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
</script>

<style type="text/css">

* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
input[type=text], textarea { width: 250px; float: left; }
textarea { height: 50px; }
</style>
</head>

<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL</span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
</form>
</body>
</html>

The code is quite straightforward and doesn't need much explanation. However, there are a few important points that I would like to bring to your attention.
Now, let us see the validate() function in detail.


$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", // simple rule, converted to {required: true}
email: { // compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters. In the example above, we use only two of them, but you can find a list of all the options for the validate() function at :

You can find an exhaustive list of built-in validation methods at Demo

If you have better solution, just tell me !

Email syntax validation using javascript

We should validate the syntax of email entered in the form in the client side itself to save unnecessary server process to validate the email.It can be done using javascript. Consider below form. onSubmit event of Form is calling a javascript function ValidateForm .


<form name="frmSample" method="post" action="" onSubmit="return
     ValidateForm();">
<p>Enter an Email Address :
<input type="text" name="txtEmail">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>

The javascript function ValidateForm is calling another function emailcheck to validate syntax of the email id.


<script language = "Javascript">

function emailcheck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){

return false //if @ symbol is not there
}

if (str.indexOf(at)==-1 str.indexOf(at)==0 str.indexOf(at)==lstr){

return false //if @ symbol available at starting or ending of email.
}

if (str.indexOf(dot)==-1 str.indexOf(dot)==0 str.indexOf(dot)==lstr){

return false //if "." is not available,
                                  or available at beginning or end of email.
}

if (str.indexOf(at,(lat+1))!=-1){

return false //if more one @ symbol available in email
}

if (str.substring(lat-1,lat)==dot str.substring(lat+1,lat+2)==dot){

return false //if no letter is available between @ and "."
}

if (str.indexOf(dot,(lat+2))==-1){

return false
}

if (str.indexOf(" ")!=-1){

return false //if blank space available in email.
}

return true
}

function ValidateForm(){
var emailID=document.frmSample.txtEmail

if ((emailID.value==null)(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (emailcheck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
</script>

If you have better solution, just tell me !

Date validation in javascript

The method below will valdiate a date.
This will not take care for 29 Feb or 30 Feb or 31 Feb
It is a basic date valdiation.


function checkDate(input) {
var validformat = /^(0[1-9]1[012])[-](0[1-9][12][0-9]3[01])[-](1920)\d\d+$/;
var returnval = true;
if (!validformat.test(input)) {
alert("The specified delivery date is invalid. Please specify the date in the proper format(MM-DD-YYYY) to continue.");
returnval = false;
}
return returnval;
}

If you have better solution, just tell me !

Ajax CalendarExtender - Date Validation

I've just been asked to find a solution to stop users choosing dates in the past in a calendarextender control. After using a little google-phoo, I found a couple of solutions which involved extending the extender itself. Altering the calendar.js then recompiling it and putting it back into your solution. That just seems a bit excessive to me. So I got to thinking couldn't I just use some in page JavaScript to trap the date entered.

First we add a text box and a calendarextender:


<asp:TextBox ID="txtDate" MaxLength="10" runat="server"
ReadOnly="True"></asp:TextBox
>

<
cc1:CalendarExtender ID="CalendarExtender1" runat="server"
Format="dd/MM/yyyy" TargetControlID="txtDate"
OnClientDateSelectionChanged="checkDate"&gt; </cc1:CalendarExtender>


you may notice that the CalendarExtender has an event attached (checkDate) - this is the JavaScript function you want it to call when ever you select a new date, add this function the top of your aspx page:


<script type="text/javascript">

function checkDate(sender,args)
{
//create a new date var and set it to the
//value of the senders selected date
var selectedDate = new Date();
selectedDate = sender._selectedDate;
//create a date var and set it's value to today
var todayDate = new Date();
var mssge = "";

if(selectedDate < todayDate)
{
//set the senders selected date to today
sender._selectedDate = todayDate;
//set the textbox assigned to the cal-ex to today
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
//alert the user what we just did and why
alert(
"Warning! - Date Cannot be in the past");
}
}
</script>


Simple and the nice thing is it's reusable for all the calendarextenders on your page, just add the checkDate function to your other extenders.

Happy Coding

Using Ajax to Validate Forms

Forms are such a common element on the Internet we tend to blunder through them without too much thought. However, if the web site has added a few nice touches that make the process easier, it tends to speed up the process and reduce any frustration in finding our preferred username (i.e. try getting your name under Hotmail!).

Howto
As with all these tutorials, I expect that you have built your solution to the point where it works, but now we want to add our splash of JavaScript magic.
In our baseline example, my requirements are:
  • Username validation kept in separate function
  • Server side does the it’s normal job
  • I can detect an Ajax request and return something different
Username validation
Our PHP function to validate the username reads:



function check_username($username) {
$username = trim($username); // strip any white space
$response = array(); // our response

// if the username is blank
if (!$username) {
$response = array(
'ok' => false,
'msg' => "Please specify a username");


// if the username does not match a-z or '.', '-', '_' then
  // it's not valid
} else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
$response = array(
'ok' => false,
'msg' => "Your username can only contain alphanumerics and period,
                  dash and underscore (.-_)");

// this would live in an external library just to check if the username is taken
} else if (username_taken($username)) {
$response = array(
'ok' => false,
'msg' => "The selected username is not available");

// it's all good
} else {
$response = array(
'ok' => true,
'msg' => "This username is free")
;
}

return $response;
}


This format for a response is good, because we are using it to display error messages on the page, but we can also convert it to JSON and use it in our Ajax response later on.

Markup

Again, it’s assumed your markup is already designed to show error messages.

For this example the following markup is being used within a fieldset.

<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="<?=@$_REQUEST['username']
                   ?>" id="username" />
<span id="validateUsername"><?php if ($error) { echo $error
                   ['msg']; }?></span>
</div>

jQuery

Our client side check will perform the following:

  • Only if the value has changed run the check, i.e. ignore meta keys
  • Use a nice ajax spinner to indicate activity
  • Make an Ajax request and show the response


$(document).ready(function () {
var validateUsername = $('#validateUsername');
$('#username').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html
                                    ('<img src="images/ajax-loader.gif"
                      height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});
}, 200);

this.lastValue = this.value;
}
});
});


Fire an ajax request in 1/5 of a second.


$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});

The actual Ajax request. If the script ajax-validation.php returns any response, convert it to JSON and put the ‘msg’ field in to the validation message.

Ajax Validation code : Download

If you have better solution, just tell me !

Validation which accept( empty, numeric or Float values)

Now we have to discuss about the validationexpression ie:

the textbox should accept empty values , numeric ( float )

.Implementation Code :
^\d*\.?\d*$
HTML



<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3"
        runat="server" ErrorMessage="Invalid format" 
ControlToValidate="TextBox3" ValidationExpression="^\d*\.?\d*$" 
ValidationGroup="d"></asp:RegularExpressionValidator>
<asp:Button ID="Button5" runat="server" Text="Button"
ValidationGroup="d" />

Matches

( ) -> empty value
4535
520.20
2.54
Non-Matches
21.0dfdf
47854
Rpks

If you have better solution, just tell me !

Ajax form validation in Confluence plugin using a JSON request

Today I describe how to make Ajax requests to XWork actions inside a Confluence plugin. A good example is server-side form validation. User fills a form, clicks Submit, then we validate the form in background and if there are no errors we allow submitting the form, otherwise show field errors.

Suppose we have a simple user info form with input fields like name, department, email etc:

<form id="saveform" action="doUpdate.action" method="post">
#tag( TextField "name='user.name'" "size='50'" )
#tag( Select "name='user.department'"
"list=departmentsDao.all"
"listKey=name" "listValue=name"
"emptyOption='true'" )
#tag( TextField "name='user.email'" "size='50'" )
...
#tag( Submit "id=userformsubmit"
"name='save'" "value='dot.button.save'"
)
#tag( Submit "name='cancel'" "value='dot.button.cancel'" )
</form>

One way to make form validation is to write it in javascript, but what if you already have it implemented in action? Write everything again? Maybe it's better to use existing server side code so you can switch on/off Ajax at any time and you'll not have the same logic implemented twice.

Here are the required steps:

edit atlassian-plugin.xml and create a package for you application with validation enabled, declare an action doUpdate for submitting a form and editValidate for Ajax validation.

<package name="userinfo" extends="default"
namespace="/dot/users"&gt;
<default-interceptor-ref name="validatingStack"/>
...
<action name="doUpdate"
class="dot.userinfo.users.action.EditUserInfo"
method="save">
<external-ref name="dotUsersDao">
usersDao</external-ref>
<external-ref name="dotDepartmentsDao">
departmentsDao</external-ref>
<external-ref name="dotCitiesDao">
citiesDao</external-ref>
<result name="input" type="velocity">
/templates/dot/userinfo/users/edituser.vm</result>
<result name="success" type="redirect"&gt;
/dot/users/usercard.action?id=${user.id}</result>
<result name="cancel" type="redirect">
/dot/users/observe.action</result>
</action>
...
<action name="editValidate"
class="dot.userinfo.users.action.EditUserInfo">
<result name="input" type="json" />
<result name="success" type="json" />
</action>
...
</package>

Action editValidate will be called in Ajax from javascript. In my experience, both input and success return types are required. input is returned in case of any field errors, success when everything is ok. Actually there is no need to return success to javascript, but instead I could save the form and redirect to another form. I'll try this in next post.

public class EditUserInfo
extends ConfluenceActionSupport
implements JSONAction {
...
public String getJSONString() {
try {
if (hasFieldErrors()) {
StringBuffer sb = new StringBuffer();
sb.append("[");
Map fieldErrors = getFieldErrors();
for (Object field : fieldErrors.keySet()) {
List<Object> msg =
(List<Object>) fieldErrors.get(field);
if (field != null && msg != null
&& msg.get(0) != null) {
sb.append("{field:'"+field+"',
error:'"+msg.get(0)+"'},");
}
}
if (sb.length() > 1) {
sb.deleteCharAt(sb.length()-1);
}
sb.append("]");
return sb.toString();
}
} catch (Exception e) {
// handle exception
}
return "";
}
}

By the time getJSONString() method is called validation was already done by WebWork so we can immediatelly process the errors. Here I generate a Javascript array of all field errors which I want to show next to input fieds. Write EditUserInfo-validation.xml file in the same package as java class. My validation file looks something like this

<validators>
<field name="user.name">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
</field>
<field name="user.department">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
</field>
<field name="user.email">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
<field-validator type="email">
<message key="dot.field.error.email" />
</field-validator>
</field>
</validators>
Main stuff is done, last thing we need is to call validation from Javascript and show error messages.
  • attach click event to submit button
$("#userformsubmit").click(function(e) {
try {
var form = $("#saveform");
validateForm(form);
} catch (e) { alert(e); }
return false; // always!
});
  • My validateForm looks like this
function validateForm(form) {
$.ajax({url: "editValidate.action",
data: form.serialize(),
success: function(data) { try {
var fields = $("#saveform span.fielderror");
// delete old errors,
// error spans are found by class name

fields.html("");
// set received errors, iterate through span IDs
data = eval(data);
if (data && data.length > 0) {
for (i in data) {
var id = data[i].field.replace(/\./, "\\.")+
"-error";
var fe = $("#"+id);
if (fe) { fe.html(data[i].error); }
}
return false;
}
$("#saveform").submit();
return true;
} catch (e) { alert(e); } }
});
return false;
}

Here for every input control I have span with id ending with '-error' and class 'fielderror'. I still haven't tried to write macros so I implemented a separate file fielderror.vm

<span id="$!webwork.htmlEncode($f)-error"
class="fielderror">
#set( $err = $fieldErrors.get($f) )
#if( $err.size() > 0 )
$err.get(0)
#end
</span>
which I include in main page next to input fields. Example for user name field:

#set( $f = "user.name" )
#parse( "/templates/dot/userinfo/fielderror.vm" )

Next week I'll try to optimize the code. In current implementation I believe validation is called twice: 1st time in ajax, and 2nd time when form is submitted (this we can escape), for field errors I need macro..