Form validation using Jquery focus and blur method - javascript

I am trying to do simple form validation by using jQuery. Actually I am try to validate the input boxes on blur and focus. I am just validating first input for now which validate user first name.It is not functioning properly.
Can any please help me?
HTML & JS CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Test
</title>
<style type="text/css">
.showerror{
display:block;
}
.noshowerror{
display:none;
}
.remerr{
display:none;
}
.redborder{
border:#F00 solid 1px;
background-color:yellow;
}
.greenborder {
border:#0F3 solid 1px;
background-color:#6F6;
}
</style>
</head>
<body>
<div style="width:450px">
<div style="float:left">
<table>
<form id="eg">
<tr>
<td>
<label>
Name:
</label>
<td>
<input type="text" id="name" />
</tr>
<tr>
<td>
<label>
Surname:
</label>
<td>
<input type="text" id="surname" />
</tr>
<tr>
<td>
<label>
Email:
</label>
<td>
<input type="text" id="email" />
</tr>
<tr>
<td>
<label>
Number:
</label>
<td>
<input type="text" id="number" />
</tr>
<tr>
<td>
<label>
Age:
</label>
<td>
<input type="text" id="age" />
</tr>
<tr>
<td>
<label>
Comment:
</label>
<td>
<input type="text" id="comment" />
</tr>
<tr>
<td>
<label>
Password
</label>
<td>
<input type="password" id="pwd" />
</tr>
<tr>
<td>
<label>
Confirm Password
</label>
<td>
<input type="password" id="cnfmpwd" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="test" />
</td>
</tr>
</form>
</table>
</div>
<div style="float:right">
<p id="fail" class="noshowerror" >
Please enter name
</p>
<p id="nameerr2" class="remerr">
Name is correct
</p>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
});
$('#name').blur(function () {
var nameRegex = /^[A-Za-z]+$/;
var fname = document.getElementById("name").value;
if (!nameRegex.test(fname)) {
$("#name").addClass('redborder');
} else if (fname == " ") {
$("#name").addClass('redborder');
} else {
$("#name").addClass('greenborder');
return false;
}
});
});
</script>
</body>
</html>
Thanks in advance

I have refined our code and its working as you intended, there were several mistake in defining the elements within table,may be you can have a look at my code on how to define it .
LIVE DEMO
HTML CODE:
<body>
<div style="width:450px">
<div style="float:left">
<form id="eg" action="/">
<table>
<tr>
<td>
<label>Name:</label>
</td>
<td>
<input type="text" id="name" />
</td>
</tr>
<tr>
<td>
<label>Surname:</label>
</td>
<td>
<input type="text" id="surname" />
</td>
</tr>
<tr>
<td>
<label>Email:</label>
</td>
<td>
<input type="text" id="email" />
</td>
</tr>
<tr>
<td>
<label>Number:</label>
</td>
<td>
<input type="text" id="number" />
</td>
</tr>
<tr>
<td>
<label>Age:</label>
</td>
<td>
<input type="text" id="age" />
</td>
</tr>
<tr>
<td>
<label>Comment:</label>
</td>
<td>
<input type="text" id="comment" />
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="password" id="pwd" />
</td>
</tr>
<tr>
<td>
<label>Confirm Password</label>
</td>
<td>
<input type="password" id="cnfmpwd" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="test" onclick="return false;" />
</td>
</tr>
</table>
</form>
</div>
</div>
<div style="float:right">
<p id="fail" class="noshowerror">Please enter name</p>
<p id="nameerr2" class="remerr">Name is correct</p>
</div>
</body>
JS CODE:
$(document).ready(function () {
if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
});
$('#name').blur(function () {
var nameRegex = /^[A-Za-z]+$/;
// var fname = document.getElementById("name").value;
var fname = $("#name").val();
alert(nameRegex.test(fname));
if (!(nameRegex.test(fname))) {
$("#name").removeClass('greenborder').addClass('redborder');
} else if (fname == " ") {
$("#name").removeClass('greenborder').addClass('redborder');
} else {
$("#name").removeClass('redborder').addClass('greenborder');
return false;
}
});
});
When your using jQuery lib, make sure you make the most of it, i have seen that there was raw javascript syntax in your code. jQuery was designed make things easier by reducing the syntax.
Edited:
I have refined the code, so that the code work on any number of times.
Happy Coding :)

$('#name').blur(function(){
trigger the blur event.
To listen for the blur event, made by the user :
$('#name').on("blur", function(){

if ($("#name").val('')) {
$("#name").val('Name Please');
}
$('#name').focus(function () {
if ($('#name').val() == 'Name Please') {
$('#name').val("");
}
can be changed by :
<input type="text" name="name" id="name" placeholder="Name Please" />
http://www.w3schools.com/tags/att_input_placeholder.asp
For your issue :
var fname = $("#name").val(); //jQuery style
$('#name').on("blur", function(){
// we want element #name a range of letters
var regexp = /^([A-Za-z])+$/;
// if the element #name contains a range of letters defined in var regexp
if (!nameRegex.test(fname)) {
$("#name").addClass('redborder');
return true;
}
// if the element #name is empty, does not contain string
if ( $("name").length === 0 ) {
$("#name").addClass('redborder');
return true;
}
// if we are still here, means that the element #name is valid
$("#name").addClass('greenborder');
return false;
}
// on focus name input
$("#name").on("focus", function() {
// if the input get the redborder class, then reset
if ( fname.hasClass("redborder") ){
fname.removeClass("redborder");
}
}

Related

My form's validate() is not working

NOTHING IS WORKING! I added onSubmit = "validate()" to my register button in the form, and I made the function and the alert if the fields are left empty. But NOTHING IS WORKING!
No alerts no errors in console. No hope!
<head>
<title>WHAT THE TECH!</title>
<script type="text/javascript">
function validate() {
let fullname = document.getElemenyByname("full_name").value;
let email = document.getElemenyById("email").value;
let pass = document.getElemenyById("password").value;
let add = document.getElemenyById("address").value;
if (fullname == "" || fullname.length == 0) {
alert("Enter Full Name");
document.getElemenyById("full_name").focus;
return false;
} else if (email == "" || email.length == 0) {
alert("Enter Email Address!");
document.getElemenyById("email").focus;
return false;
}
}
</script>
</head>
<body>
<div class="mainwrap">
<div class="content">
<div class="SignUp">
<div class="Formup">
<div class="title">New here? Register!</div>
<form name="register">
<table>
<tr>
<td>Full Name: </td>
<td><input type="text" id="full_name">
</td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email">
</td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password">
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<select>
<option value="U.A.E">U.A.E</option>
<option value="K.S.A">K.S.A</option>
<option value="Qatar">Qatar</option>
</select>
</td>
</tr>
<tr>
<td>Gender: </td>
<td>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</td>
</tr>
<tr>
<td>Address: </td>
<td><input type="text" id="address">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Register" class="registerbutton" name="register" onSubmit="validate()">
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
You should use document.getElementsByName if you want to fetch the value using name attribute. I would recommend to do it by "id" attribute.
function submitFunction() {
var firstName = document.getElementsByName("first_Name")[0].value;
if (firstName == "" || firstName == null || firstName.length == 0) {
alert("First Name is required");
return false;
}
}
Also add return to the onsubmit event to avoid page refresh.
<form name="Register" onsubmit="return submitFunction() " method="post">
Option 2 : Using HTML5
The required attribute will do the validation check and you can skip javascript.
<input type="text" name="first_Name" required>

how to disable the button based on result of javascript function

I want to disable the button based on the javascript result of textboxes if there is incorrect email id then the button should be disabled .Help me over this.If there is incorrect email and phone no ,I Want to disable my Button function or button.My problem is I'm using separate javascript functions for textboxes so how can disable the button based on other javascript function.Help me over this
<div align="right">
</div>
<div id="div">
<center> <h3>REGISTER</h3></center>
<div id="output" align="center">
</div>
<table>
<thead>
</thead>
<tbody>
<tr>
<td>
<label>Firstname</label>
<td>
<input type="text" name="firstname" id="firstname" required="">
</td>
</tr>
<tr>
<td>
<label>Lastname</label>
</td>
<td>
<input type="text" name="lastname" id="lastname" required="">
</td>
</tr>
<tr>
<td>
<label>Email</label>
</td>
<td>
<input type="text" name="email" id="email" required="">
</td>
<td id="error" style="display:none;color:red">
invalidemail
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="password" name="password" id="password" required="">
</td>
</tr>
<tr>
<td>
<label>Confirm password</label>
</td>
<td>
<input type="password" name="confirmpassword" id="confirmpassword" required="">
</td>
<span id="pass"></span>
</tr>
<tr>
<td>
<label>Phone no</label>
</td>
<td>
<input type="text" name="phoneno" pattern="[789][0-9]{9}" id="phoneno" required="" maxlength="10">
</td>
<td id="invalidphone" style="display:none;color:red">
invalidphoneno
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submit" value="submit" id="submit"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
Login?
</td>
</tr>
</tbody>
</table>
</div>
</body>
</head>
</html>
<script type="text/javascript">
$('#email').on('keypress', function() {
var re = /([A-Z0-9a-z_-][^#])+?#[^$#<>?]+?\.[\w]{2,4}/.test(this.value);
if(!re) {
$('#error').show();
} else {
$('#error').hide();
}
});
$('#phoneno').on('keypress',function(){
var phone=/^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}/.test(this.value);
if(!phone){
$('#invalidphone').show();
}
else
{
$('#invalidphone').hide();
}
});
$(document).ready(function(){
$('#submit').click(function(){
var first=$('#firstname').val();
var last=$('#lastname').val();
var Email=$('#email').val();
var pass=$('#password').val();
var confirm=$('#confirmpassword').val();
var phone=$('#phoneno').val();
$.ajax({
type:"POST",
url:"register.php",
data:{
firstname:first,
lastname:last,
email:Email,
password:pass,
confirmpassword:confirm,
phoneno:phone,
},
success:function(data){
if($.trim(data)==='successfully registered')
{
$('#output').html(data);
}
else
{
$('#pass').html(data);
}
},
error:function()
{
alert("error");
}
});
});
});
</script>
Have submit button disabled initially till you have all form
elements as proper
With the HTML5 input (email and text) fields, you already have the required attribute present, but need to put required="required"
Have an onChange event for the last (required) field, check if the
validation is successful.
Check this for more details and additional info
If input field is empty, disable submit button
Use $("#submit").attr("disabled", true); to disable and $("#submit").removeAttr("disabled"); to enable the button
$('#phoneno').on('keypress',function(){
var phone=/^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}/.test(this.value);
if(!phone){
$("#submit").attr("disabled", true); // disable submit btn
$('#invalidphone').show();
}
else
{
$("#submit").removeAttr("disabled"); //enable submit btn
$('#invalidphone').hide();
}
});
Simply disable the button at the top of your javascript.
$("#submit").prop("disabled", true);
Then in your regex, if it's true, set it to false.
EDIT - It's probably best to set your regex variables global and then you can do if statement for both regex.
if (re && phone) {
$("#submit").prop("disabled", false);
}

Javascript Validating username Length

I am trying to validate my username field and check if the username contains atleast 6 letters, if not then i show a pop up window indicating the same.
But the alert command does not seem to work.
Following is the code:
<html>
<head>
<title> Webpage </title>
</head>
<script language="Javascript">
function validate()
{
if (username1.length < 6)
{
alert("Username must be atleast 6 charactrs long, Please Try Again");
}
}
</script>
<body>
<form>
<center>
<fieldset>
<table cellspacin="5" cellpadding="5" border="0">
<tr>
<td>Username: </td>
<td align="left"><input type=="text" name="username1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Password: </td>
<td align = "left"> <input type="text" name="password" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Please confirm your password: </td>
<td align = "left"> <input type="text" name="password1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td align="center"><input type="submit" value="Log in" onClick="validate()">
</td>
</tr>
</fieldset>
</table>
</center>
</form>
</body>
</html>
You are trying to use the name element attribute as the id, which creates a global window property. Name does not do that however, you can use.
You also aren't getting the value, you are trying to get the length on the element.
document.getElementsByName('username1')[0].value
Answer:
I tried it this way it worked:
<html>
<head>
<title> Webpage </title>
</head>
<script language="Javascript">
function validate()
{
username2 =form1.username1.value
if (username2.length < 6)
{
alert("Username must be atleast 6 charactrs long, Please Try Again");
}
}
</script>
<body>
<form name="form1">
<center>
<fieldset>
<table cellspacin="5" cellpadding="5" border="0">
<tr>
<td>Username: </td>
<td align="left"><input type=="text" name="username1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Password: </td>
<td align = "left"> <input type="text" name="password" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Please confirm your password: </td>
<td align = "left"> <input type="text" name="password1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td align="center"><input type="submit" value="Log in" onClick="validate()">
</td>
</tr>
</fieldset>
</table>
</center>
</form>
</body>
</html>

A readonly textbox should be cleared on checkbox checked

<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)"/>
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="myFunction(this)" />
</td>
</tr>
</table>
I want to clear textbox when we corresponding checkboc is checked. Here is my Java script,
<script type="text/javascript" language="javascript">
function CheckCheckboxes1(chk){
if(chk.checked == true)
{
var txt = document.getElementById('TextBox1');
txt.value = "";
txt.disabled = false;
}
else
{
var txt = document.getElementById('TextBox1');
txt.value = "Enter Username";
txt.disabled = true;
}
}
</script>
Any idea?
In order to get the corresponding textbox, you can't get it by ID. Instead you should get the inputs parent table row and then find the input from there, so that it is relative to the checkbox.
Working demo
function CheckCheckboxes1(chk){
var txt = chk.parentNode.parentNode.cells[2].getElementsByTagName('input')[0];
if(chk.checked == true)
{
txt.value = "";
txt.readOnly = false;
}
else
{
txt.value = "Enter Username";
txt.readOnly = true;
}
}
Notes:
Use txt.readOnly not txt.disabled because disabled is something different.
Use the checkbox onchange event not onclick.
Hi in order to disable and enable you need to assign the id's to both checkbox and textboxs. please look at the below code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
function CheckCheckboxes1(chk){
if(chk.checked == true)
{
var txt = document.getElementById('TextBox'+chk.id);
txt.value = "";
txt.disabled = false;
}
else
{
var txt = document.getElementById('TextBox'+chk.id);
txt.value = "Enter Username";
txt.disabled = true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox1" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" id="1" onclick="CheckCheckboxes1(this)"/>
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox2" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="2" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>`enter code here`
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox3" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="3" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox4" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="4" onclick="myFunction(this)" />
</td>
</tr>
</table>
</body>
</html>
As #Adil said it is easier if you use jQuery. You can give your textbox an id and your checkbox a cutstom attribute e.g.:
<td>
<input type="text" id="txt_1" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" specId="1" onclick="CheckCheckboxes1(this)"/>
</td>
function CheckCheckboxes1(chk){
var specId = $(chk).attr("specId");
var txt = $("#txt_"+specId);
if(chk.checked == true)
{
$(txt).val("");
$(txt).attr("disabled","disabled");
}
else
{
$(txt).val("Enter Username");
$(txt).removeAttr("disabled");
}
}
Hope it helps!

Validation password not working

I am working on sign up form using html form , but i am facing problem my password cannot validate when I enter wrong password and enter write past does not show anything so what should i do any help.
function validate(){
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
if (pass==pas1)
{
}
else
{
alert("Try again");
}
}
</script>
</head>
<body>
<p class="style2 style8">SIGN UP FORM!!!!</p>
<form onclick="validate()" action="insert.php" method="post">
<table width="270" height="386" border="1" align="right" bordercolor="#993366" bgcolor="#CCCCCC"><td width="260"><table width="232" border="1">
<tr>
<td colspan="2"><span class="style2">loginform</span></td>
</tr>
<tr>
<td width="72"><span class="style5">Name</span></td>
<td width="144"><label>
<input name="name" type="text" id="name" onblur="MM_validateForm('name','','R');return document.MM_returnValue" placeholder="Name" />
</label></td>
</tr>
<tr>
<td width="72"><span class="style5">Gender</span></td>
<td><p>
<label>
<input type="radio" name="gender" value="Male" id="gender"/>
<span class="style5">Male</span></label>
<span class="style5" onfocus="MM_validateForm('fname','','R');return document.MM_returnValue"><br />
<label>
<input type="radio" name="gender" value="female" id="gender" />
female</label>
</span><br />
</p></td>
</tr>
<td width="72"><span class="style5">DOB</span></td>
<td width="144"><span id="sprytextfield1">
<label>
<input name="dob" type="text" id="dob" onblur="MM_validateForm('dob','','R');MM_validateForm('dob','','R');return document.MM_returnValue" placeholder="yyyy/mm/dd"/>
</label>
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span></td>
</tr>
<tr>
<td><span class="style5">Password</span></td>
<td><label>
<input name="pwd" type="password" id="pwd" onchange="MM_validateForm('pwd','','R');return document.MM_returnValue" placeholder="password"/>
</label></td>
</tr>
<tr>
<td width="72"><span class="style5">Confirm Password</span></td>
<td width="144"><label>
<input name="cpwd" type="password" id="cpwd" onchange="MM_validateForm('cpwd','','R');return document.MM_returnValue" placeholder="Confirm Password"/>
</label> </td>
</tr>
<tr>
<td colspan="2"><label>
<div align="center">
<input type="submit" name="submit" id="submit" value="Signup" />
</div>
</label></td>
</tr>
</table>
<label></label></td>
</tr>
</table>
</form>
<h1> </h1>
<script type="text/javascript">
<!--
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "date", {format:"yyyy/mm/dd"});
//-->
</script>
</body>
</html>
there is no pass in your content. You are writing it as:
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
Which should be this:
var pass = (document.getElementById("pwd").value;
var pas1 = (document.getElementById("cpwd").value;
Because the variable's name comes before the = sign. To show that this variable is having this value!
So, now lets use this one and try it like this:
if(pass==pas1) {
// save the password or whatever
} else {
// please try again..
}
This way, the user will check the inputs again. And it they are not working. Then you must first check that whether you are using correct ID of the element, or you are using ClassName as ID!
That's what the issue might be.
Well, for starters,
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
should be
var pass = document.getElementById("pwd").value;
var pas1 = document.getElementById("cpwd").value;
Edit:
Also, change onclick="validate()" to onclick="return validate();" and add return false; after the alert("Try again");.
Just small change in your code
function validate(){
var pass = document.getElementById("pwd").value;
var pas1 = document.getElementById("cpwd").value;
if (pass==pas1){
}
else{
alert("Try again");
return false;
}
}

Categories

Resources