Phone number regex - javascript

i want to check regular expression and if it doesn't match alerts 'invalid' but my problem is regular expression doesn't work
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '' || !$("#PhoneField").match(phonePattern) == false) {
alert("it is invalid")
}
}
i worked with this code in javascript pure it worked but in jquery doesnt work
this is whole jquery code snippet:
<script>
$(document).ready(function() {
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '') {
alert("it is invalid")
}
var phoneField = $("#PhoneField").val();
$.ajax({
type:'post',
url:'insert.php',
data:{'phoneField':phoneField},
success:(function (response) {
})
})
$.ajax({
type:'post',
url:'show.php',
data:{},
success:(function (response) {
$("#CodeField").val(response);
})
})
});
});

If you are sure that your regular expression is the right one, then you need to change your code as follows (the match string method does not return a boolean, it's either an array with the matches or null) :
$("#SendPhone").click(function() {
var phonePattern = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/;
if ($("#PhoneField").val() == '' || !$("#PhoneField").match(phonePattern)) {
alert("it is invalid");
}
});

Related

How to use two forms in the Ajax request?

var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$('#login' || '#lostpasswordform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
The question is how to use two forms in one request with ajax. In this code I used ||, but it doesn't work. I mean the #login form works well but the #lostpasswordform doesn't work. When I click on the button it reloads the page instead of giving an alert.
The reason for this is the way you do your jQuery selection. Selecting multiple elements is done like this: $( "div, span, p.myClass" )
In other words it should work if you replace $('#login' || '#lostpasswordform') with $('#login, #lostpasswordform')
You can read more in detail about this in the jQuery docs
elector be used to select multiple elements. $("#login,#lostpasswordform").submit()
Use below code :
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$("#login,#lostpasswordform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}

Ajax Login not returning results

I've created a login box in a modal, but I'm not able to get the results back for some reason. I'm very new to javascript, so I'm guessing it's something obvious!
$('#login').click(function()
{
$("#buttons").hide();
$("#progress").show();
var email=$("#email").val();
var password=$("#password").val();
var dataString = 'email='+email+'&UserPW='+password;
if($.trim(email).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "includes/php/ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#buttons").hide();
$("#progress").show();
;},
success: function(data){
if(data)
{
console.log(data);
if (data = "client/staff")
{
$("#clientStaffToggleButtons").show();
}
if (data = "staff")
{
$("body").load("staff/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data = "client")
{
$("body").load("myevent/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data = "noEmail")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
if (data == "noPW")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
}
});
}
return false;
Any ideas on what may be wrong?
Much thanks!! :D
EDIT
Just to clarify, I'm getting the functions back (through console log) but they don't seem to be actually doing anything in the if-then statements, for example:
if (data = "client/staff")
doesn't seem to be doing anything, even if data returned was "client/staff"
to test it out go to fiestausa.com and hit login on the top-right
You're using the assignment operator (=), instead of the comparison operator (=== or == if you don't care about the type), so stuff like this:
if (data = "client/staff")
should become this:
if (data === "client/staff")
The assignment operator returns the assignment value, so in your case the if line from above equals to:
data = "client/staff";
if ("client/staff")
and that evaluates to true since a non-empty strings are truthy.
Incorrect use of comparisons:
$('#login').click(function(e)
{
e.preventDefault();
$("#buttons").hide();
$("#progress").show();
var email=$("#email").val();
var password=$("#password").val();
var dataString = 'email='+email+'&UserPW='+password;
if($.trim(email).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "includes/php/ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#buttons").hide();
$("#progress").show();
;},
success: function(data){
if(data.d)
{
console.log(data.d);
if (data.d == "client/staff")
{
$("#clientStaffToggleButtons").show();
}
if (data.d == "staff")
{
$("body").load("staff/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data.d == "client")
{
$("body").load("myevent/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data.d == "noEmail")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
if (data.d == "noPW")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
}
});
}
"return false" is now deprecated.

Jquery with variable selector doesn't work

I don't know why the selector jquery doesn't accept a variable.
function myfunction()
{
$.ajax({
url: "/file.php", dataType: "json", type: "GET",
success: function(data)
{
var data = data.split("-");
data.forEach(function(entry)
{
if (entry != "")
{
$("#check_status_" + entry).html('text');
}
});
}
});
}
variable entry is not empty, the problem is when I put it into the selector.
Thanks.
[update]
{
var test = "aaa-bbb-ccc";
var data = test.split("-");
data.forEach(function(entry) {
if (entry != ""){
$("#check_status_" + entry).html('!NEW!');
}
});
}
nothing the same
It seems to work fine if you are achieving something like this
data.forEach(function(entry) {
if (entry) {
$("#check_status_" + entry).html('text');
}
});

JavaScript Validation error?

I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?
The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});

How to make nested call with jquery

I've below code in JS file:
$(document).ready(function() {
$("#key_verify").click(function () {
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
if($.trim($("#key").val()).length != 0){
$.ajax({
type : "POST",
cache : false,
async : true,
url : "/issuekey?key="+$("#key").val(),
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj === undefined || json_obj == null){
}else{
if(json_obj.result == "true"){
top.location.href="/register"
}else{
$("#errrmsg").html(invalid_key);
}
}
},
error : function(data) {
$("#errrmsg").html(invalid_product_key);
}
});
}
});
}
How can I invoke above code in below lines so that when user hits enter key, it should make a call on enter key as well??
$("#key_verify").keypress(function(e) {
if(e.which == 13){
??????
}
});
Thanks!
Make the function you are passing to the click handler into a named function like so:
var verify = function(e) {
// your current anonymous function
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
// ... the rest of your function
}
Then pass it as an argument into your event handlers:
$("#key_verify").click( verify );
$("#key_verify").keypress(function(e) {
if(e.which == 13){
verify( e );
}
});

Categories