You are on page 1of 26

Module IV Part II

Form Handling & Validation


What is form validation?
• Consider a registration form,
• "This field is required" (You can't leave this field blank).
• "Please enter your phone number in the format xxx-xxxx" (A specific data
format is required for it to be considered valid).
• "Please enter a valid email address" (the data you entered is not in the right
format).
• "Your password needs to be between 8 and 30 characters long and contain
one uppercase letter, one symbol, and a number." (A very specific data format
is required for your data).

• This is called form validation. When you enter data, the browser
and/or the web server will check to see that the data is in the correct
format and within the constraints set by the application.
What is form validation?
• Validation done in the browser is called client-side validation,
while validation done on the server is called server-side
validation.
Why form validation is important?
• We want to get the right data, in the right format. Our
applications won't work properly if our users' data is stored
in the wrong format, is incorrect, or is omitted altogether.
• We want to protect our users' data. Forcing our users to
enter secure passwords makes it easier to protect their
account information.
• We want to protect ourselves. There are many ways that
malicious users can misuse unprotected forms to damage
the application
Different types of client-side validation
• Built-in form validation uses HTML5 form validation
features. This validation generally doesn't require
much JavaScript. Built-in form validation has better
performance than JavaScript, but it is not as
customizable as JavaScript validation.
• JavaScript validation is coded using JavaScript. This
validation is completely customizable, but you need to
create it all (or use a library).
Using built-in form validation
• One of the most significant features of HTML5 form controls is the ability to
validate most user data without relying on JavaScript. This is done by using
validation attributes on form elements.
• required: Specifies whether a form field needs to be filled in before the form
can be submitted.
• minlength and maxlength: Specifies the minimum and maximum length of
textual data (strings)
• min and max: Specifies the minimum and maximum values of numerical input
types
• type: Specifies whether the data needs to be a number, an email address, or
some other specific preset type.
• pattern: Specifies a regular expression that defines a pattern the entered data
needs to follow.
• If the data entered in a form field follows all of the rules specified by the above
attributes, it is considered valid. If not, it is considered invalid.
The required attribute
<form>
<label for="choose">Would you prefer a
banana or cherry?</label>
<input id="choose" name="i_like“ required>
<button>Submit</button>
</form>
Constraining the length of your entries and value
<form>
<div>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input type="text" id="choose" name="i_like" required minlength="6"
maxlength="6">
</div>
<div>
<label for="number">How many would you like?</label>
<input type="number" id="number" name="amount" value="1" min="1"
max="10">
</div>
<div>
<button>Submit</button>
</div>
</form>
Regular Expression
• A regular expression is a sequence of characters that forms a
search pattern.
• Syntax:
/pattern/modifiers;
• Example:
var patt = /webprogramming/i;

– / webprogramming/i is a regular expression.


– webprogramming is a pattern (to be used in a search).
– i is a modifier (modifies the search to be case-insensitive).
Regular Expression modifiers
• Regular Expression Modifiers
Modifier Description
i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the
first match)
m Perform multiline matching
• Regular Expression Patterns
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Regular Expression modifiers
• Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
\s Find a whitespace character

• Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Validating against a regular expression

<form>
<label for="choose">Would you prefer a banana or a cherry?
</label>
<input id="choose" name="i_like" required
pattern="[Bb]anana|[Cc]herry">
<button>Submit</button>
</form>
Validating Checkbox status
<script>
function checkForm(form)
{
if(document.getElementById("terms").checked==false) {
alert("Please indicate that you accept the Terms and Conditions");
form.terms.focus();
return false;
}
return true;
}

</script>

<form onsubmit="return checkForm(this);">


<p><input type="checkbox" id="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
Username Patterns
• Only letters (either case), numbers, and the underscore; no more than
15 characters.
• [A-Za-z0-9_]{1,15}
• Only lowercase letters and numbers; at least 5 characters, but no
limit.
• [a-zd.]{5,}
• Only letters (either case), numbers, hyphens, underscores, and
periods. (Not the slash character, that is being used to escape the
period.) The username must start with a letter and must be between 1
and 20 characters long (inclusive).
• [a-zA-Z][a-zA-Z0-9-_.]{1,20}
Payment Info Patterns
• Credit Card Format - Digits only, between 13 and 16 digits long.
• [0-9]{13,16}
• URL input pattern:
• "https?://.+“
• IPv4 Address input pattern:
• "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}“
• Date input pattern (dd/mm/yyyy or mm/dd/yyyy):
• "\d{1,2}/\d{1,2}/\d{4}“
• Price input pattern:
• "\d+(\.\d{2})?"
JavaScript Form Validation
• It is important to validate the form submitted by the user
because it can have inappropriate values.
• Validation is must to authenticate user.
• JavaScript provides facility to validate the form on the client-
side so data processing will be faster than server-side
validation.
• Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email,
date, mobile numbers and more fields.
Validate the name and password
<script>  
function validateform(){  
var name=document.getElementById(“name”).value;  
var password=document.getElementById(“password”).value;   
  
if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
  }  
}  
</script>  
validate the name and password
<body>  
<form name="myform" method="post" action="abc.jsp"
 onsubmit="return validateform()" >  
Name: <input type="text" name="name“ id="name“
><br/>  
Password: <input type="password" name="password“
id="password"><br/>  
<input type="submit" value="register">  
</form>  
JavaScript Retype Password Validation
<script type="text/javascript">  
function matchpass(){  
var firstpassword=document.getElementById(“password”).value;  
var secondpassword=document. .getElementById(“password2”).value;  
  
if(firstpassword==secondpassword){  
return true;  
}  
else{  
alert("password must be same!");  
return false;  
}  
}  
</script>  
  
JavaScript Retype Password Validation

<form name="f1" action="register.jsp" onsubmit="return matchpass()">  
Password:<input type="password" name="password"  id=“password”/><br/>  
Re-enter Password:<input type="password" name="password2“
id=“password2”/><br/>  
<input type="submit">  
</form>  
  
  
JavaScript Number Validation
<script>  
function validate(){  
var num=document.getElementById(“num”).value;  
if (isNaN(num)){  
  document.getElementById("numloc").innerHTML="Enter Numeric value only";  
  return false;  
}else{  
  return true;  } }  
</script>  
<form name="myform" onsubmit="return validate()" >  
Number: <input type="text" name="num“ id=“num”>
<span id="numloc"></span><br/>  
<input type="submit" value="submit">  
</form>  
JavaScript Email Validation
• We can validate the email by the help of JavaScript.
• There are many criteria that need to be follow to validate the email id
such as:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
JavaScript Email Validation
<script>  
function validateemail()  
{  
var x=document.getElementById(“email”).value;  
var atposition=x.indexOf("@");  
var dotposition=x.lastIndexOf(".");  
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
  alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
  return false;  
  }  
}  
</script>  
JavaScript Email Validation

<body>  
<form name="myform"  method="post" action="#"
 onsubmit="return validateemail();">  
Email: <input type="text" name="email“
id=“email”><br/>  
  
<input type="submit" value="register">  
</form> 
</body>

You might also like