Check Username Using Ajax in Jquery Validation Engine - javascript

I am using query Validation Engine :
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I want to validate the username field using ajax. If username already exisit in db.. It should validate.
Here is my code & something I have tried so far :
JS:
"ajaxUserNameCheck": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
HTML:
<input class="validate[custom[ajaxUserNameCheck]" type="text" name="userName" id="userName" ></div>
It returns an error in alert:
jqv:custom type not allowed ajaxUserNameCheck

<input class="validate[custom[ajaxUserNameCheck]" type="text" name="userName" id="userName" ><span id="emailinfo" ></span>
$(document).ready(function(){
$("#userName").focusout(function(){
var e = $(this).val();
$.ajax({
type: "POST",
url: "username_validate.php", //AJAX FILE
data: {e: e},
success: function(e)
{
if(e == 0)
{
$("#emailinfo").hide();
}
else
{
$("#emailinfo").html(e);
}
}
});
});
});

Replace
validate[custom[ajaxUserNameCheck]
with
validate[ajax[ajaxUserNameCheck]

The custom rules are defined in jquery.validationEngine-en.js under section
CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
Any modifications should be made there. Hope this helps.
Also you are missing a "]" close square brackets in your class=" syntax
class="validate[ajax[ajaxCaptchaCallPhp]]

Related

Javascript XMLHttpRequest and Jquery $.ajax both are returning the current page HTML code

The problem
Hello i want to start off hoping all of y'all are having a fantastic day! I'm having a really weird problem that i have never came across before. I have a bootstrap navigation form with two fields, an input for a email and a field for the password.
When the user submits the form it calls to an AddEventListener which is waiting for a click of the login button. and after that is called it validates(Server Side Validation) the form of the entered data. After both the email_validated and password_validated is both equal to true it calls to a function called checkLogin(email, password){email = entered email in field, password = entered password in field}. In the checkLogin function it called to a JQuery $.ajax({}) call which sends the email and password field to a php document located in /scripts/checkLogin.php. However instead of it returning "Hello"(For testing purposes) is returns the entire HTML code for the current page(As shown above)
JQuery $.ajax({}) code
Here i have the code for the $.ajax({}) call.
Console
I'm not getting any errors in the console except for the XHR finished loading: POST
Other Pictures
Here are some other pictures that i am including to hopefully give yall a better idea of the structure.
Note
I just want to add that i have checked Stackoverflow for similar problems and other people have had this problem but they solutions did not work on my code. I have also tried just using a regular XMLHttpRequest and the same problem occurred, i'm honestly not sure what is wrong with the code for i have never had this problem before. Thank you for taking the time to read this i appreciate any help that i can get with solving this. I'm not the best with $.ajax({}) or XMLHttpRequest and im willing to make any changed to the code to try to get this to work. Below is my code for the entire javascript validation(server side).
Code
<form class="form-inline my-2 my-lg-0" method="POST">
<input class="form-control mr-sm-2 nav-login" type="text" autocomplete="off" placeholder="Email" name="email" value="trest#gmail.com" id="email">
<input type="password" name="password" autocomplete="off" class="form-control nav-login mr-sm-2" placeholder="Password" value="password" name="password" id="password">
<button class="btn btn-success my-2 my-sm-0 nr" type="button" name="login_button" id="login_button">Login <i class="fas fa-sign-in-alt"></i></button>
</form>
<script>
document.getElementById('login_button').addEventListener('click', (e) => {
e.preventDefault();
// const email_regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let email_validated = true;
let password_validated = true;
let email = document.getElementById('email');
let password = document.getElementById('password');
// let email_length = email.value.length;
// let password_length = password.value.length;
//
//
// if(!email_length){
// email.classList.add('is-invalid');
// }else{
// if(!email_regex.test(email.value)){
// email.classList.add('is-invalid');
// }else{
// email.classList.remove('is-invalid');
// email.classList.add('is-valid');
// email_validated = true;
//
// }
// }
// if(!password_length){
// password.classList.add('is-invalid');
// }else{
// password.classList.remove('is-invalid');
// password.classList.add('is-valid');
// password_validated = true;
// }
if(email_validated === true && password_validated === true){
checkLogin(email.value, password.value);
}
});
function checkLogin(email, password){
$.ajax({
type: "POST",
url: '/scripts/checkLogin.php',
data: {
'email': email,
'password': password
},
contentType: "application/json; charset=utf-8",
success: (result) => {
alert(result);
}
});
}
</script>
Links to the other StackOverFlow question
ajax returns the html code of current page instead of json
I was the way my server was configured with xammp as t.niese said.

Why won't this script load?

I have a contact us form:
<form id="contactus" name="contactus" action="html_form_send1.php" method="post">
<label for="name">Name:</label><br />
<input type="text" id="name" name="name" maxlength="50" size="59" autofocus required/><br /><br />
<label for="email">E-Mail Address:</label><br />
<input type="email" id="email" name="email" maxlength="50" size="59" required/><br /><br />
<label for="question">Question:</label><br />
<textarea id="question" name="question" maxlength="1000" cols="50" rows="6" required></textarea><br /><br />
<input class="c1_scButton" type="submit" id="submit" name="submit" value="Send" />
</form>
I want it to call my mail PHP script using this AJAX code:
var msg = "";
name = $("#name").val();
email = $("#email").val();
question = $("#question").val();
//validation phase
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
function validate(e) {
if (name == "") {
msg = " valid name";
}
if (!isValidEmailAddress(email)) {
msg = msg + " valid email address";
}
if (question == "") {
msg = msg + " valid question or comment";
}
}
// on submit, Validate then post to PHP mailer script
$(function() {
$("#contactus").on('submit', function(e) {
e.preventDefault();
validate(e);
if msg != "" {
e.preventDefault();
$("#alert").html "Please enter a" + msg;
} else {
$.post('/html_form_send1.php', $(this).serialize(), function(data) {
$('#alert').css(color: "black")
$('#alert').html("<h2>Thank you for contacting us!</h2>")
.append("<p>We will be in touch soon.</p>");
}).error(function() {
$('#alert').css(color: "red")
$('#alert').html("<h2>Something went wrong. Your Question was not submitted. /n</h2>").append("<p>Please try again later or email us at <a href=href="
mailto: support# allegroaffiliates.com ? Subject = Contact Us Form " target="
_top ">support#allegroaffiliates.com.</a> </p>");
});
};
});
});
The script is called at the bottom of the HTML page after another script, but it isn't loading. I suspect that it is due to a code error but I can't find the error. Can anybody give me an idea why it wont load?
Side note: I do know that HTML5 will validate the script, but I have the validation in place for when HTML5 is not available.
Thank you for your help.
A few troubleshooting suggestions:
(1) When specifying the ajax processor file, either this $.post('html_form_send1.php' or this $.post('./html_form_send1.php' but not this $.post('/html_form_send1.php'
(2) Instead of using the shortcut code $.post(), use the full form of the method until you are pretty good at it:
var varvalue = $('#first_name').val();
var nutherval = $('#last_name').val();
$.ajax({
type: 'post',
url: 'your_secondary_file.php',
data: 'varname=' +varvalue+ '&lname=' +nutherval,
success: function(d){
if (d.length) alert(d);
}
});
(3) Disable validation routine until the rest is working, then work on that when you know everything else is working correctly
(4) Change your ajax processor file html_form_send1.php to just echo back a response to make sure you've got the AJAX working. Then, once you get the response, change it to echo back the variable you are sending. Then build it into the final desired product. But initially, something dead simple, like this:
your_secondary_file.php:
<?php
$first_name = $_POST['varname'];
$last_name = $_POST['lname'];
echo 'Received: ' .$first_name .' '. $last_name;
die();
(5) Instead of using .serialize(), initially just grab one or two field values manually and get that working first. Note that .serialize() produces JSON data, while the simpler method is straight posted values, as in sample code in this answer. Get it working first, then optimize.
(6) Note that the dataType: parameter in the AJAX code block is for code coming back from the PHP side, not for code going to the PHP side. Also note that the default value is html, so if you aren't sending back a JSON object then just leave that param out.
(7) In my AJAX and PHP code samples above, note the correlation between the javascript variable name, how it is referenced in the AJAX code block, and how it is received on the PHP side. I was very deliberate in the names I chose to allow you to follow the var name => var value pairing all the way through.
For example, the input field with ID first_name is stored in a variable called varvalue (dumb name but intentional). That data is transmitted in the AJAX code block as a variable named varname, and received on the PHP side as $_POST['varname'], and finally stored in PHP as $first_name
Review some simple AJAX examples - copy them to your system and play with them a bit.

jQuery validation with input mask

Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.
I use:
https://github.com/RobinHerbots/jquery.inputmask
https://github.com/1000hz/bootstrap-validator
(which uses jQuery native validation in this case)
Some strange behaviors:
Inputs with attribute required are validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)
When i write something into input field and then erase it, I get required error message
Can anyone give me some hint?
EDIT:
Relevant code:
HTML/PHP:
<form enctype="multipart/form-data" method="post" id="feedback">
<div class="kontakt-form-row form-group">
<div class="kontakt-form">
<label for="phone" class="element">
phone<span class="required">*</span>
</label>
</div>
<div class="kontakt-form">
<div class="element">
<input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php">
</div>
</div>
<div class="help-block with-errors"></div>
</div>
</form>
JS:
$(document).ready(function() {
$('#phone').inputmask("+48 999 999 999");
$('#feedback').validator();
});
I managed to use the RobinHerbots's Inputmask (3.3.11), with jQuery Validate, by activating clearIncomplete. See Input mask documentation dedicated section:
Clear the incomplete input on blur
$(document).ready(function(){
$("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});
Personnaly, when possible, I prefer setting this by HTML data attribute:
data-inputmask-clearincomplete="true"
The drawback is: partial input is erased when focus is lost, but I can live with that. So maybe you too ...
Edit: if you need to add the mask validation to the rest of your jQuery Validate process, you can simulate a jQuery Validate error by doing the following:
// Get jQuery Validate validator currently attached
var validator = $form.data('validator');
// Get inputs violating masks
var $maskedInputList
= $(':input[data-inputmask-mask]:not([data-inputmask-mask=""])');
var $incompleteMaskedInputList
= $maskedInputList.filter(function() {
return !$(this).inputmask("isComplete");
});
if ($incompleteMaskedInputList.length > 0)
{
var errors = {};
$incompleteMaskedInputList.each(function () {
var $input = $(this);
var inputName = $input.prop('name');
errors[inputName]
= localize('IncompleteMaskedInput_Message');
});
// Display each mask violation error as jQuery Validate error
validator.showErrors(errors);
// Cancel submit if any such error
isAllInputmaskValid = false;
}
// jQuery Validate validation
var isAllInputValid = validator.form();
// Cancel submit if any of the two validation process fails
if (!isAllInputValid ||
!isAllInputmaskValid) {
return;
}
// Form submit
$form.submit();
It's not exactly the solution, but...
changing inputmask for some equivalent solves the problem.
Still far from perfect, though : (
EXPLANATION:
Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.
I used:
https://github.com/digitalBush/jquery.maskedinput
I have the same issue when combined these two libs together.
Actually there is a similar ticket here: https://github.com/RobinHerbots/Inputmask/issues/1034
Here is the solution provided by RobinHerbots:
$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});
The validator assumes that it is not empty when the mask focus/hover is there.
simply turn focus and hover of the mask off will fix the problem.
I solved this problem with:
phone_number: {
presence: {message: '^ Prosimy o podanie numeru telefonu'},
format: {
pattern: '(\\(?(\\+|00)?48\\)?)?[ -]?\\d{3}[ -]?\\d{3}[ -]?\\d{3}',
message: function (value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^ Nieprawidłowa wartość w polu Telefon");
}
},
length: {
minimum: 15,
message: '^ Prosimy o podanie numeru telefonu'
},
},

JavaScript form validation issue - submit has to be clicked twice

JavaScript code of validation- https://freedigitalphotos.net/images/js/judd-validate.js
We have some new forms on our website which have client side JavaScript validation.
The validation is triggered when the user "defocuses" from the form fields. The validation is a combination of AJAX (checking database for valid user names etc) and JavaScript (checking fields not blank, or contain expected data).
The user has to click the form submit button twice to send the form. It seems that the first click is triggering the field validation but not submitting the form. Clicking for a second time successfully completes the form.
Go to- https://freedigitalphotos.net/images/recover_password.php
Type arifkpi#gmail.com in the email field, and then immediately hit submit. Again, notice that the first click merely validates the input, using AJAX it is checking the email address is in the database. A second click is required.
I want to fix this, so everything will work with a single click.
Instead of calling Ajax validations on focustout event, you can call it on click of your button and if Ajax returns true result then submit form programatically. Refer few sample code lines:
Html Part:
<form method="post" id="registration_form" name="registration_form" action="register.php">
EmailId: <input type="text" id="email_id" name="email_id">
<label class="error" for="username" id="globalErrorUsername"></label>
Username: <input type="text" id="username" name="username">
<label class="error" id="globalErrorEmail"></label>
<button type="button" id="register_btn" name="register_btn">Register</button>
</form>
Js Part:
$("#register_btn").click(function() {
//.valid function is useful when you are using jquery Validate library for other field validation
if ($('#registration_form').valid()) {
var email_id = $('#registration_form').find('#email_id').val(),
username = $('#registration_form').find('#username').val();
$.ajax({
beforeSend: function() {
$('#globalErrorUsername').html('');
$('#globalErrorEmail').html('');
}, //Show spinner
complete: function() { },
type : 'post',
url : 'check-user-existence.php',
dataType :'json',
data : 'email_id=' + email_id + '&username=' + username,
success:function(response) {
if(response.success == 1) {
//submit the form here
$("#registration_form").submit();
} else if (response.error == 1) {
if(response.details.username != undefined) {
$('#globalErrorUsername').show();
$('#globalErrorUsername').html(response.details.username);
}
if(response.details.email_id != undefined) {
$('#globalErrorEmail').show();
$('#globalErrorEmail').html(response.details.email_id);
$('#email_id').focus();
} else {
$('#username').focus();
}
}
}
});
} else {
return false;
}
return false;
});

jQuery validate plugin on DIV

I am trying to use the validate plugin on a div as shown in the answer to this question:
<script type="text/javascript">
$("#pseudoForm").validate({
onfocusout:true,
rules:{
first_name:"required",
last_name:"required"
}
});
</script>
<!-- whatever -->
<div id="pseudoForm">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
</div>
I have all within a form.
I am getting a bunch of different errors on different browsers.
Firefox: validator in undefined
IE8: 'settings' is null or not an
object
Chrome: Cannot read property 'settings' of undefined
Any help appreciated!
This isn't the answer you want to hear, but the other answer is incorrect (it may have been right when it was posted, but there have been several major jQuery validation plugin changes since then).
The validation plugin is (currently) designed to work on a <form>, and only on a <form>. You can also note that all of the plugin documentation references a form, not any other generic container.
The plugin itself keeps track of validator.currentForm internally, which refers to the this of the passed in selector, getting .elements, etc off that...it's really not going to work any other way, not the way the current version's written.
The overall solution/alternative approach here: call .validate() on the <form> element (the jQuery wrapper for it rather) directly, not any other container. If you need to divide your <form> use <fieldset> elements, possibly using the ignore: ':hidden' option in .validate() if you don't want to validate input fields that aren't visible to the user.
You're missing a closing bracket. Try this instead:
$("#pseudoForm").validate({
onfocusout:true,
rules:{
first_name:"required",
last_name:"required"
}
});
You can get the same error if you select the form by class
$(".form_class").validate(...
instead of by ID
$("#form_id").validate(...
or tag name
$("form").validate(...
Open jquery.validate.js or jquery.validate.min.js and find(ctrl + F) "label" and replaceAll with your your required tag:
Example: div
then perform validation.
//HTML
<div class="form-group has-feedback col-xs-8 " style="padding-right:0px">
<input type="tel" class="form-control" name="Otp_MobileNo" id="mobileNo" placeholder="Mobile No." minlength="10" maxlength="10">
<span id="mobileno_message" style="display:none;color: red;">Please enter a valid Mobile No</span>
</div>
//Java Script
$("#getOtp").click(function(){
jQuery(document).ready(function(){
var MobileNo = jQuery("#mobileNo").val();
var MobileNoLength = MobileNo.length;
var zipRegex = /^\d{10}$/;
var mobileNo = $("#mobileNo").val();
if (!zipRegex.test(MobileNo))
{
jQuery('#mobileno_message').show();
}
else
{
// success!
jQuery('#mobileno_message').hide();
$.ajax({
type : 'POST',
url : '<?php echo site_url('Login/send_otp'); ?>',
data : {Otp_MobileNo:mobileNo,},
dataType : 'json',
beforeSend: function()
{
$("#error").fadeOut();
},
success : function(response)
{
alert(response.message_text);
$("#check-otp").delay().animate({
height: 'toggle',
},
"slow");
$("#getOtp").hide();
}
});
}
});
});

Categories

Resources