Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.
Related
How do I test for form validation for both variables: emailAddr && items[].
items[] is a checkbox array.
Currently the code below won't submit the form at all.
jQuery(document).ready(function(){
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
var emailValue = email.value;
var testEmail = re.test(emailValue);
jQuery("#submitForm").on("click",function(){
if (jQuery("input[name*='items']").is(":checked"),
testEmail === true){
return true;
} else {
jQuery('#messages').append("You must choose at least 1 image<br>
Please enter a valid email");
return false;
}
});
});
Cleaning up the code a little to check for the value on submission may help but I do not know exactly how the html is formatted to see why else the form may not be submitting.
var re = /(\w+)\#(\w+)\.[a-zA-Z]/g;
var email = document.getElementById("emailAddr");
jQuery("#submitForm").on("click",function(e){
var emailValue = email.value;
var testEmail = re.test(emailValue);
if (jQuery("input[name*='items']").is(":checked") && testEmail === true){
return true;
} else {
e.preventDefault(); // prevents the form from submitting if invalid
jQuery('#messages').append("You must choose at least 1 image<br>Please enter a valid email");
return false;
}
});
I'm trying to validate my interactive PDF. So if i click on a button (for validating) there's following code behind it:
var isBlank = false;
var blank = "Please fill following fields:";
var isNotValid = false;
var notValid = "Please check input data in following fields:";
var message = "";
var t = ['Division', 'Oragnisationseinheit', 'Name', 'KZZ', 'Privataddresse'];
var i;
for(var i=0; i<t.length;i++){
//validation text fields needs to be filled in
if (this.getField(t[i]).value == "") {
blank = blank + "\n" + this.getField(t[i]).name;
isBlank = true;
}
//validation text field must contain only lower case letters
if (/^[a-z]*$/.test(this.getField(t[i]).value) == false) {
notValid = notValid + "\n" + this.getField(t[i]).name;
isNotValid = true;
}
//generate message
if (isBlank == true) {
message = blank + "\n" + "\n";
}
if (isNotValid == true) {
message = message + notValid;
}
}
//check all conditions
if ((isBlank == true) || (isNotValid == true)) {
//show message
app.alert({ cMsg: message, cTitle: "Input data error" });
}
The problem is now, if I press the button there's no reaction. --> the var message wont being displayed. Where is the issue?
Thanks for all ideas.
You might try instead to add a custom validation script that would first check to be sure the field isn't blank and if not, simply change the input to lower case so the user doesn't need to modify the field themselves.
Add the following code to the custom field validate script. This should work for any text field.
if (event.value.length == 0) {
app.alert({ cMsg: event.target.name + " cannot be blank.", cTitle: "Input data error" });
}
else {
event.value = event.value.toLowerCase();
}
I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.
First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.
You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer
The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
So my script perfectly checks whether username is free or not but regardless of that when user submits all forms he is able to register. I need a way to prevent user from registering if username is taken. Here is the code:
index.php
$("#username").keyup(function(){
var val=$("#username").val();
$("#address").html("Your address will be askfolio.com/" + val);
$("#freeu").html("<img src='css/ajax-loader.gif' style='margin-left:-75px;'>");
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:$("#username"),
success:function(data){
if (data == 1){
$("#freeu").html("<img src='css/accept.png' style='float:left;padding-right:65px;'>");
$("#reg-error").css("display","none");
}else{
$("#freeu").html('');
$("#reg-error").css("display","block");
$("#reg-error").html('Username is already taken, try another.');
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
});
function Users_Registration()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#name").val();
var lastname=$("#lastname").val();
var username = $("#username").val();
var remail = $("#remail").val();
var rpass = $("#rpass").val();
var day=$("#day").val();
var month=$("#month").val();
var year=$("#year").val();
if(name == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your name in the required field.');
$("#name").focus();
}
else if(lastname == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html(' Please enter your Last Name in the required field.');
$("#lastname").focus();
}
else if(username == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your desired username to proceed.');
$("#username").focus();
}
else if(remail == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your email address to proceed.');
$("#remail").focus();
}
else if(reg.test(remail) == false)
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid email address to proceed.');
$("#remail").focus();
}else if (rpass == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid password to proceed.');
$("#rpass").focus();
}
else if (day == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a day to proceed.');
$("#day").focus();
}else if (month == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a month to proceed.');
$("#month").focus();
}else if (year == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a year to proceed.');
$("#year").focus();
}
else
{
var dataString = 'name='+ name + '&lastname='+ lastname + '&username='+ username + '&rpass='+ rpass + '&remail='+ remail + '&year=' + year + '&month=' + month + '&day=' + day +'&page=signup';
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#reg-error").html('<br clear="all"><div style="padding-left:115px;"><font style="font-family:Verdana, Geneva, sans-serif; font-size:12px; color:black;">Please wait</font> <img src="images/loadings.gif" alt="Loading...." align="absmiddle" title="Loading...."/></div><br clear="all">');
},
success: function(response)
{
$("#reg-error").html("Loading");
var username="<?php echo $loguser; ?>";
window.location=username;
}
});
}
}
ufree.php
<?php
include "db.php";
if (isset($_POST['username'])) {
$username=$_POST['username'];
$sql=mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($sql) == 0) {
echo "1";
}else {
echo "<div style='padding-top:4px;'>username is taken</div>";
}
}
?>
Apart from the SQL Injection vulnerability that you have in your sql queries, your approach to username check is somewhat redundant. By checking the username upon every character input you add extra load to the browser and to your server.
I suggest you combine the two processes in one step meaning you do the username check and register in the same place. In your Register.php file check the username availability right before the registration and if the username is taken display a proper message and if not do the registration.
Goes without saying but regardless of the javascript validation, your server still needs to be checking that the username is available at point of registering, since anyone can disable or manipulate the javascript.
Also as Hamed states, your php code is highly vulnerable. At the very least, you should use the following prior to using it in your sql:
$username = mysql_real_escape_string( $_POST[ 'username' ] );
That said, for usability, what you need to do is add an onsubmit function to your form, which checks if the username is valid or not prior to submitting. (summarised your code for simplicity)
var validUser = false;
$("#username").keyup(function(){
var val=$("#username").val();
validUser = false;
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:val,
success:function(data){
if (data == 1){
validUser = true;
}else{
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
function formsubmit()
{
if( !validUser )
{
alert( 'Username is already taken, try another' );
return false;
}
return true;
}
Then in your form:
<form action="whatever" onsubmit="return formsubmit();">
...
</form>
Once of my favorite jQuery plugin is the validation eng.
https://github.com/posabsolute/jQuery-Validation-Engine
It has very nice validation for doing just what you are looking for. It does all kinds of fields including inline ajax for username check. If the response from ajax call is not true, then the form won't submit. I use it for my signup forms. Once the user goes to the next field it validates, if it doesn't pass i.e. the username is not available, it will say username not available in red. The form won't submit.
It's not hard to setup. Here is a demo of the ajax. Note it won't actually validate on this demo site but it's an example. You can see how it won't submit though if it's blank or not validated. It's very customizable.
http://www.position-relative.net/creation/formValidator/demos/demoAjaxSubmitPHP.html
Oh course take care of any mysql security issues and check to make sure dupes can't be entered into the database as well.
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.