Email Address and Phone Validation | jQuery - javascript

Having some trouble getting validation to work for Email and Phone on an input field.
Basically I'm after validation on the email input when it is selected. Phone validation - mainly to check for numbers used.
I found jQuery Validate and referenced that in my demo.
This is my first time to Reg Ex Validation and got a little confused so was hoping someone could help me on that front.
The phone validation is working however, I can't seem to figure out how to meet the requirements of the field when testing. It's also asking email as a required field.
Ultimately, a user has to input either a valid email or phone number so validation or error handling will need to be done for that too which I can do.
DEMO HERE
Here is my jQuery:
var ebuForm = {
init : function() {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val() =="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone : function() {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
}
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function() {
ebuForm.init();
});

Working Fiddle Example: http://jsfiddle.net/775X2/56/
Your HTML:
<form id="myform">
<div class="grid4">
<input type="radio" checked="checked" tabindex="50" class="left" name="x" id="email" value="email" />
<label for="email" class="left marginRight20">Email</label>
<input type="radio" tabindex="60" class="left" name="x" id="phone" />
<label for="phone" class="left">Phone</label>
<br />
<input type="text" class="email-input" name="emailer" placeholder="Email Address" />
<input type="text" class="phone-input" name="phone" placeholder="Phone Number" />
</div>
</form>
Validation Documentation
Some jQuery:
var ebuForm = {
init: function () {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput: function (e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function () {
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if ($(this).val() == "email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone: function () {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
},
emailer: {
required: true,
email: true
},
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function () {
ebuForm.init();
});

Related

Error text is not being displayed for function result

I've successfully used the definition on other pages before. Basically it should make the field required, but fail if only whitespace is entered (by default typing i.e. a single space causes the required check to pass). I tossed an alert in just to see when the handler is fired as well as the value of this at that time. It's fired when I expect it, and the value is as I expect it. It should be returning false but apparently it isn't because the error isn't being displayed. If I remove that depends function and just have required: true, it correctly displays the error when the user leaves the field. What's going on?
ContactName: {
required: {
depends: function() {
alert("'" + $(this).val() + "'");
if ($.trim($(this).val()).length === 0) {
$(this).val($.trim($(this).val()));
return false;
}
return true;
}
},
maxlength: 100
}
You can change the rule for ContactName like (for details take a look to rules examples):
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
The snippet:
$("#commentForm").validate({
rules: {
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
},
messages: {
ContactName: "Please enter your contact name"
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="ContactName">Name</label>
<input id="ContactName" name="ContactName" type="text">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

Put two JavaScript functions together for one button? (JavaScript/HTML)

I have 2 separate functions working that use 2 different buttons, however I want to put them together for so that both functions are triggered simultaneously under one button.
I have a user registration form, and I have one function that sends the data into the database, and the other function checks if the username is existing or not.
What I need is for when the user submits the form, the form should not be submitted if the username already exists, thus an alert should appear saying for example "username taken, please try another". Nevertheless, if username has not been taken, then submit the form.
Can someone shed some light on how I can go about this and put both these functions together for the same button?
Register Function -
function registerUser() {
var Username = document.getElementById("txtusername").value;
var Firstname = document.getElementById("txtfirstname").value;
var Lastname = document.getElementById("txtlastname").value;
var Email = document.getElementById("txtemail").value;
var Password = document.getElementById("txtpassword").value;
var Confirmpass = document.getElementById("passwordconfirm").value;
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(function(tx) {
NewUser(tx, Username, Firstname, Lastname, Email, Password, Confirmpass);
}, errorRegistration, successRegistration);
}
function NewUser(tx, Username, Firstname, Lastname, Email, Password, Confirmpass) {
var _Query = ("INSERT INTO SoccerEarth(UserName, FirstName, LastName, Email, Password, CPass) values ('"+ Username +"','"+ Firstname +"','"+ Lastname +"','"+ Email +"', '"+ Password +"', '"+ Confirmpass +"')");
alert(_Query);
tx.executeSql(_Query);
}
function errorRegistration(error) {
navigator.notification.alert(error, null, "Got an error mate", "cool");
}
function successRegistration() {
navigator.notification.alert("User data has been registered", null, "Information", "ok");
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#page4" );
}
Check username in database function-
function CheckUser()
{
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(UserDB, errorCB);
}
function UserDB(tx)
{
alert("user check");
var User = document.getElementById("txtusername").value;
tx.executeSql("SELECT * FROM SoccerEarth WHERE UserName='" + User + "'", [], renderUser);
}
function renderUser(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("Username is taken, please try again.");
}
else
{
navigator.notification.alert("Username available!");
}
HTML -
<form id="form1" data-ajax="false">
<div data-role="fieldcontainer">
<label for="txtusername" data-theme="d">Username:</label>
<input type="text" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
</div>
<div data-role="fieldcontainer">
<label for="txtfirstname" data-theme="d">First Name:</label>
<input type="text" id="txtfirstname" name="txtfirstname" placeholder="Enter First Name"/>
</div>
<div data-role="fieldcontainer">
<label for="txtlastname" data-theme="d">Last Name:</label>
<input type="text" id="txtlastname" name="txtlastname" placeholder="Enter Last Name"/>
</div>
<div data-role="fieldcontainer">
<label for="txtemail" data-theme="d">Email:</label>
<input type="email" id="txtemail" name="txtemail" placeholder="Enter Enter Email"/>
</div>
<div data-role="fieldcontainer">
<label for="txtpassword" data-theme="d">Password:</label>
<input type="text" id="txtpassword" name="txtpassword" maxlength="12" placeholder="Enter Password"/>
</div>
<div data-role="fieldcontainer">
<label for="passwordconfirm" data-theme="d">Confirm Password:</label>
<input type="text" id="passwordconfirm" name="passwordconfirm" maxlength="12" placeholder="Confirm password"/>
</div>
<br>
<input type="submit" value="Register User">
Input Validations (JQUERY) -
$('#form1').submit(function (e) {
e.preventDefault();
}).validate({
rules: {
txtusername: {
required: true
},
txtfirstname: {
required: true
},
txtemail: {
required: true
},
txtpassword: {
required: true
},
passwordconfirm: {
required: true
}
},
messages: {
txtusername: {
required: "Please enter your Username."
},
txtfirstname: {
required: "Please enter your First Name."
},
txtemail: {
required: "Please enter your Email."
},
txtpassword: {
required: "Please enter your Password."
},
passwordconfirm: {
required: "Please enter your password again."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form, user) {
registerUser(form);
return false;
}
});
I can see in your code that you check if the username is available, so you can use the event onchange
<input type="text" onchange="CheckUser()" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
so when the user write some your function CheckUser() is activated, after that you can use normally , inside of
if (results.rows.length > 0) {
navigator.notification.alert("Username is taken, please try again.");
} else {
//add event click only if is available your username
navigator.notification.alert("Username available!");
element = document.getElementById("btnSend");
element.addEventListener("click", registerUser())
}
and write your input submit with this id btnSend
<input id="btnSend" type="submit" value="Register User">
So in this way you validate if the username is available only in this case you add RegisterUser() for your submit
last but not least be more careful because you wrote code in your JS (Query for DB) and this can be affecty your security
Create new function which call this 2 functions
function newfunction()
{
// you need to return true/false from check user function
if(CheckUser())
{
registerUser();
}
}
and call this on onclick
<input type="submit" value="Register User" onclick="newfunction()">
Use a onsubmit event to handle the registration
<form id="form1" data-ajax="false" onsubmit="doSubmit();">
and javascript function will look like
function doSubmit(){
// check if the user exists. Return a boolean value to return the status
var userExists = checkUser();
// if user exists, return false to protect form from submitting.
if(userExists){
return false;
}
// if user does not exists, register the user
registerUser();
}

How to validate fields without form tag?

Following is my code
HTML
<input type="submit" onclick="OpenDialog()" value="Add Record" />
<div id="AddBox" style="display: none">
<label>Install</label>
<input type="text" id="Install" />
<label>Payout</label>
<input type="text" id="Payout" />
<label>Start Date</label>
<input type="text" id="reqStartDate" value="#ViewBag.StartDate" name="reqStartDate" readonly="true" />
<label>End Date</label>
<input type="text" id="reqEndDate" value="" name="reqEndDate" readonly="true" />
</div>
JS
<script type="text/javascript">
function OpenDialog() {
$('#AddBox').dialog({
title: 'New Client',
autoOpen: false,
resizable: false,
show: {
effect: "slide",
duration: 800
},
hide: {
effect: "fold",
duration: 800
},
buttons: {
"Add":function onsave() {
$.ajax({
url: '#Url.Action("BountyMatrix", "Marketing")',
type: 'POST',
data: {
clientkey: $('#reqClientID').val(),
install: $('#Install').val(),
payout: $('#Payout').val(),
StartDate: $('#reqStartDate').val(),
EndDate: $('#reqEndDate').val()
},
success: function (data) {
alert('Success');
$('#AddBox').dialog('close');
location.reload();
},
error: function (data) {
alert('Try Again :(');
}
});
}
},
height: 370,
width: 440,
modal: false
});
var name = $('#Name').val();
var address = $('#Address').val();
$('#Dialog-Name').val(name);
$('#Dialog-Address').val(address);
$('#AddBox').dialog('open');
}
</script>
I have a button that opens a dialog box,it contains textboxes without form tag,button in dialog box post a form.I just wanted to add validation to textboxes that if these boxes are empty the form should not be submitted.How should i do it using jquery validation ?
you can simply check for the value in the boxes on submit the form . i.e. on clicking the submit button. suppose your submit button has the id of "submit_button" then:
$("#submit_button").click(function(){
if ($("#text_field1").val() == "")
alert('please fill the required field')
else if ($("#text_field2").val() == "")
alert('please fill the required field')
else
return true;
});
i guess you are looking for something like this
http://jsfiddle.net/FJqVV/
you can validate like this.
if($("#Install").val()=='')
return false;
use this in OpenDialog() function, for each textbox you want to validate write else if.

jQuery Validation - Add custom callback function, check if a string has a space doesn't working

This is my code, checkUsername function doesn't working, how should I fixit?
<form id="register_form" method="post" action="">
<fieldset>
<legend>Info</legend>
<div>
<label>Username</label>
<input type="text" name="username" id="username"/>
<input type="submit" id="btnAccess" class="button" value="Submit" name="btnAccess"/>
</fieldset>
</form>
$(document).ready(function() {
var validator = $('#register_form').validate({
rules: {
username: {
required: true,
minlength: 4,
checkUsername: true
}
},
messages: {
username: {
required: "No blank",
minlength: "Enter atleast 4 words"
}
}
});
$.validator.addMethod('checkUsername', function(value, element) {
return /\s/g.test(value);
}, "error");
});
http://jsfiddle.net/nambatre/rEpqr/
P/S: if I want to check a string has some words as #, # etc, what should I do?
You need to return true is the the value is true
it should be
$.validator.addMethod('checkUsername', function(value, element) {
return this.optional(element) || !/\s/g.test(value);
}, "error");
Demo: Fiddle

Jquery Validation on cloned elements

I am using the following JQuery validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have the following element:
<div class="form-item">
<label for="Reference_name" class="required">Name: <span class="required">*</span></label>
<input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">
</div>
I have cloned the element but the validation is only appearing on the first element. I would like it to validate against the second too and show the error message label.
Can someone help with this please.
elements must be unique
<label for="Reference_name" class="required">Name:<span class="required">*</span></label>
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />
File Js
$(document).ready(function() {
validate_form();
});
function validate_form() {
$("#id_of_your_form").validate({
rules: {
'Reference_name': {
required:true,
minlength: 2,
}
},
},
messages: {
'Reference_name': {
required:"Your name is required",
minLength:'Your name is too short'
},
}
});
}
if you want to compare two fields
http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other
Put your validation function in a global variable like this:
var validate_form_function = function(){
if($(".app-form").length > 0){
$('.app-form').validate({
rules: {
comment_message: {
required: true,
minlength: 2
}
},
messages: {
comment_message: {
required: "Your message",
minlength: "Your message"
}
}
});
}
};
Then revalidate your cloned form with the function like this :
validate_form_function();

Categories

Resources