how to validate 10 digit phone number? - javascript

I need to 10 digit number validation in JS code. I've put the "Contact already exists" validation code from the databse. But I'm not recognize the 10 digit validation code.
my js code:
function checkcontact() {
var contact=document.getElementById( "UserContact" ).value;
if(contact.length==10) {
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {
u_contact:contact,
},
success: function (response) {
if(response=="not_exist") {
return true;
} else {
$( '#contact_status' ).html(response);
}
}
});
}
}
my input type from
<input class="form-control" type="text" maxlength="10" id="UserContact" onkeyup="checkcontact(); if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" placeholder="Contact Number Here" required/>
<span id="contact_status"></span> </div>
How to validate 10 digit number in checkcontact() function in js code ?

try this,
function checkcontact(){
var contact=document.getElementById( "UserContact" ).value;
var validate = check(contact);
if(validate){
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {
u_contact:contact,
},
success: function (response) {
if(response=="not_exist"){
return true;
}
else{
$( '#contact_status' ).html(response);
}
}
});
}
}
function check(var number){
var reg = /^[0-9]{1,10}$/;
var checking = reg.test(number);
if(checking){
return true;
}else{
return false;
}
}

Try this..
var val = contact
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
return false
}
Reference

Just use this to validate whether the string is only number or not
var yourValue = '123456789';
var isNumber = /^\d+$/.test(yourValue);
alert(isNumber);

Check this code
$(function() {
$('#UserContact').blur(function() {
var contact = $("#UserContact").val();
if(contact.length==10){
alert(contact)
//return false;
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {u_contact:contact},
success: function (response) {
if(response=="not_exist"){
return true;
}
else
{
$( '#contact_status').html(response);
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input class="form-control" type="number" maxlength="10" id="UserContact" placeholder="Contact Number Here" required/>
<span id="contact_status"></span> </div>

You don't need to validate 10 digits, just bind with input type as Number.
It allow only numbers as an input.
As per your code when its length will be 10 so automatically it will call ajax.
<input class="form-control" type="number" maxlength="10" id="UserContact" onkeyup="checkcontact(); if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" placeholder="Contact Number Here" required/>
<span id="contact_status"></span>

Related

How to call 2 javascript function simeltaneously

I want to check emailid format as well as check weather that email id exists in the database simultaneously as soon as the user moves to next field.
MY HTML CODE:
<input type="email"
name="mail"
placeholder="Email Address"
required="required"
onkeyup="checkuser(this.value)"
onblur="validateEmail(this);"/>
MY JAVASCRIPT CODE:
function chckuser(val)
{
$.ajax({
type:"POST",
url:"checkuser.php",
data: 'mail='+val,
success: function(data){
$("#msg").html(data);
}
});
}
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
You should runs these 2 functions inside another function.
Example:
function handleBlur(emailField) {
if ( ! validateEmail(emailField)) { return false; }
chckuser(emailField.value);
}
function chckuser(val)
{
$.ajax({
type:"POST",
url:"checkuser.php",
data: 'mail='+val,
succss: function(data){
$("#msg").html(data);
}
});
}
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
<input type="email" name="mail" placeholder="Email Address" required="required" onblur="handleBlur(this);"/>
Since Javascript is run in one thread in the browser you cannot do two things at same time. However I would first check just the email address format, if it is valid then make call to the back-end to check if it exists.

Javascript not waiting for ajax with bootstrap-wizard.js

I have a bootstrap-wizard as follows:
<div class="wizard-card" data-cardname="credential">
<h3>Credential</h3>
<div class="wizard-input-section">
<p>Username</p>
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" />
</div>
</div>
<p>Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassword" name="Bpassword" placeholder="Password" />
</div>
</div>
<p>Re-type Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassowrd2" name="Bpassword2" placeholder="Retype Password"/>
</div>
</div>
</div>
</div>
The input <input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" /> calls the checkNameAvailable function to make validation.
checkNameAvailable function:
Which makes an ajax call to check if the name is available or not.
function checkNameAvailable(el){
if($("#"+$(el).attr('id')).parsley().isValid()){
var data = $(el).val();
if($(el).attr('id') == "Busername"){
var type = "B";
}else{
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
async: false,
data: {Busername: data, _token: $("#_token").val(), _type: type },
success: function(msg) {
var retValue = {};
if(msg == "OK"){
retValue.status = true;
console.log(retValue);
return retValue;
}else{
retValue.status = false;
console.log(retValue);
return retValue;
}
}
});
}
}
The problem is that the variable retValue is not returned to the bootstrap-wizard validation.
However if i try like this it works but not when implementing with ajax
function checkNameAvailable(el){
var retValue = {};
retValue.status = false;
return retValue;
}
Any idea how to make it work with ajax? I have tried callbacks and methods described in Javascript function not waiting for AJAX responsebut it is still not working.
You can try to change your function like this:
function checkNameAvailable(el){
var dfd = $.Deferred();
if($("#"+$(el).attr('id')).parsley().isValid()){
var data = $(el).val();
if($(el).attr('id') == "Busername"){
var type = "B";
}else{
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
data: {Busername: data, _token: $("#_token").val(), _type: type },
success: function(msg) {
var retValue = {};
if(msg == "OK"){
retValue.status = true;
console.log(retValue);
dfd.resolve(retValue);
}else{
retValue.status = false;
console.log(retValue);
dfd.resolve(retValue);
}
}
});
}
return dfd.promise();
}
// after this you can use
// checkNameAvailable in this
// way.
checkNameAvailable(el).done(function(retValue) {
console.log(retValue);
});
Read my comment and example of function usage. When we using promise
the code can be asynchronous. You must not async: false - this is not
very good idea at all.
Edit:
Synchronous ajax request is not very good idea but existing code
base expect synchronous function so your function must be
changed in this way:
function checkNameAvailable(el) {
var result;
if ($("#" + $(el).attr('id')).parsley().isValid()) {
var data = $(el).val();
if ($(el).attr('id') == "Busername") {
var type = "B";
} else {
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
async: false,
data: {
Busername: data,
_token: $("#_token").val(),
_type: type
},
success: function(msg) {
var retValue = {};
if (msg == "OK") {
retValue.status = true;
console.log(retValue);
result = retValue;
} else {
retValue.status = false;
console.log(retValue);
result = retValue;
}
}
});
}
return result;
}
Good luck.
Edit 2:
I have forked the repository of project and add example how to use
asynchronous into validator function. This solution is kind of dirty
hack but is much better than using synchronous logic.
https://github.com/gonaumov/bootstrap-application-wizard/blob/master/demo/demoAsynchronousValidator.html
I also do a pull request with this changes.

Validating individual form inputs with javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});
You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO
This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Can not get ajax callback to a function

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return true means that the email address is already existed in database.
Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors.
I tried to read and follow this article but fails after so many attempts.
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
});
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return false; // good to go
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return true; // This email is registered. Please try different one
}
}
});
}
First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.
So
$(document).ready(function () {
$('#regname').focus();
$('#signupForm').submit(function (e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
//prevent the form submit
e.preventDefault();
if (regname.val() == '') {
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
} else if (regpass.val() == '') {
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
} else {
emailCheck().done(function (r) {
if (r) {
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
} else {
$('#signupForm')[0].submit();
}
});
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {
regemail: regemail.val()
};
var deferred = jQuery.Deferred();
$.ajax({
type: 'POST',
cache: false,
data: UrlToPass,
url: 'emailcheck.php',
success: function (responseText) {
if (responseText == 0) {
deferred.resolve(false);
} else {
emailcheck.html('<span class="errorss"> This email is existed.</span>');
deferred.resolve(true);
}
},
error: function () {
deferred.reject();
}
});
return deferred.promise();
}
You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.
Your function returns before the Ajax call receives its output. Use
async: false
$.ajax({
type : 'POST',
cache: false,
async: false,
data : UrlToPass,
Refer to following for dettails:
How to make JQuery-AJAX request synchronous

Prevent AJAX form from submitting twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur?
HTML
<form class="submit-form" method="post">
<input type="url" class="content-link" name="content_link" placeholder="Link" />
<input type="email" class="email" name="email" placeholder="Your Email Address" />
<button class="submit-modal-button submit-button"><span>Send<span class="ss-icon">send</span></span></button>
<p class="terms">By clicking Submit you agree to our Terms & Conditions</p>
</form>
JavaScript
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]'),
viewport_size = $(window).width() + "x" + $(window).height(),
user_browser = BrowserDetect.browser,
user_os = BrowserDetect.OS,
current_page = document.location.href;
$('.submit-form input[type="url"],.submit-form input[type="email"]').blur(function () {
if ($.trim($(this).val()) == '') {
$(this).addClass('form-validation-error');
return false;
} else {
$(this).removeClass('form-validation-error');
}
});
form.submit(function () {
if ($.trim(content_link.val()) == '' && $.trim(email.val()) == '') {
content_link.addClass('form-validation-error');
email.addClass('form-validation-error');
return false;
}
else if ($.trim(content_link.val()) == '') {
content_link.addClass('form-validation-error');
return false;
}
else if ($.trim(email.val()) == '') {
email.addClass('form-validation-error');
return false;
} else {
var env = TTB.getEnvironment();
$('.submit-modal-button').attr('disabled','disabled');
$(document).ajaxStart(function () {
$('.submit-modal .screen-1').delay(300).append('<span class="loading2"></span>');
});
$.ajax({
url: env.submit_modal_process,
type: 'POST',
data: {
    content_link: content_link.val(),
    email: email.val(),
viewportsize: viewport_size,
browser: user_browser,
os: user_os,
current_page: current_page
  },
success: function () {
$('.submit-modal .screen-1').delay(1000).fadeOut(300, function () {
$('.submit-modal .screen-1').fadeOut(500, function () {
$('span.loading2').detach();
$('.submit-modal .screen-2').fadeIn(500, function () {
$('.submit-modal .screen-2').append('<img class="carlton" src=' + env.the_environment + TTB.config.image_path() + 'submit-modal-success.gif' + ' />');
});
$('.submit-modal .screen-2').css('display','block').delay(4200).fadeOut(500, function () {
$('.carlton').hide();
$('.submit-modal .screen-1').fadeIn(500);
content_link.val('');
email.val('');
content_link.focus();
email.removeClass('form-validation-error');
$('.submit-modal-button').removeAttr('disabled');
});
});
});
}
});
return false;
}
});
}
EXAMPLE.processSubmitModal();
If to remove all non relevant to the issue code from your snippets we will get the following:
HTML
<form class="submit-form" method="post">
<input type="url" name="content_link" />
<input type="email" name="email" />
<button>Send</button>
</form>
JavaScript
$(function() {
var EXAMPLE = {
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]');
form.submit(function () {
$.ajax({
url: document.location.href,
type: 'POST',
data: {
content_link: content_link.val(),
email: email.val()
},
success: function () { // <-- The function that is executed twice
// Do something
}
});
return false;
});
}
};
EXAMPLE.processSubmitModal();
// And somewhere in the code that was not presented in snippet...
EXAMPLE.processSubmitModal();
});
I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.
Try like this
form.submit(function (event) {
if(event.handled !== true)
{
//put your ajax code
event.handled = true;
}
return false;
});
Refernce

Categories

Resources