jQuery - form validation - javascript

I am trying to write my own form validation script with jQuery.
However, I can't seem to get it to work, It's probably something minor but I can't find the cause of the problem.
Also, I have only just started using jQuery an I am looking for a good syntax checker. Can anyone recommend one?
$(document).ready(function() {
$('.error').toggle();
});
//when the button is clicked
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
return false;
}
var name = $("input#email").val();
if (name == "") {
$("label#name_error").show();
return false;
}
var name = $("input#subject").val();
if (name == "") {
$("label#name_error").show();
return false;
}
var name = $("textarea#message").val();
if (name == "") {
$("label#name_error").show();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});

Make sure you include jQuery.validate.min.js or jquery.validate.unobtrusive.min.js (cant remember off top of my head) file(s) and then validate inside jQuery like this:
$('.button').click(function () {
if ($('form').valid()) {
//do saving stuff
} else {
//errors on form - let user correct them
}
});
As far as Syntax checker, not sure what platform your developing on but Im using Visual Studio 2010 and if you include the js files then VS2010 gives intellisense which highlights issues.

<script type="text/javascript">
$(document).ready(function() {
$("#MyForm").validate({
rules: {
name: {required: true},
phone:{required: true},
email:{required: true}
},
messages: {
name: {required: "Please Enter Name"},
phone:{required: "Please Enter Phone No"},
email:{required: "Please Enter Email "}
} ,
submitHandler: function(form) {
form.submit();
}
});
});
</script>

Related

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

After submit the login page Getting error as HTTP Error 405.0 - Method Not Allowed [duplicate]

This question already has an answer here:
validate login & redirect to success page using jquery validate plugin [closed]
(1 answer)
Closed 8 years ago.
Working on login page using jquery validate plugin. After enter the correct username and password validation was working fine I created with the help of jquery validate. But the page was nto redirect to success page.
I am getting an Error as HTTP Error 405.0 - Method Not Allowed
Here is the code
$(document).ready(function () {
$("#form1").validate({
debug: false,
errorClass: "error error_red",
rules: {
username: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
messages: {
username: "Please enter a valid email address",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
success: function (data) { // for demo
$('#username').focus();
}
}
});
$('#submit').click(function () {
alert("check click");
var ValEmail = $('#username').val() == 'admin#admin.com'; // Email Value
alert("Email" + ValEmail);
var ValPassword = $('#password').val() === 'admin'; // Password Value
if (ValEmail === true && ValPassword === true) { // if ValEmail & Val ValPass are as above
alert('valid!'); // alert valid!
var site_url = 'http://localhost:55170/home_page.html';
alert("site_url" + site_url);
jQuery("#submit").click(function (event) {
alert("submit click" + jQuery("#submit").click);
window.location.href = site_url + "event-form";
});
// go to home.html
}
else {
alert('not valid!'); // alert not valid!
}
});
});
Here is the fiddle Link
Thanks in advance
M
I altered your code. try this...
Problems
You are using '===' for comparing password.
You are using same '===' in the if condition loop
$('#submit').click(function () {
alert("check click");
var ValEmail = $('#username').val() == 'admin#admin.com'; // Email Value
alert("Email" + ValEmail);
var ValPassword = $('#password').val() == 'admin'; // Password Value
if (ValEmail == true && ValPassword == true) { // if ValEmail & Val ValPass are as above
alert('valid!'); // alert valid!
var site_url = 'home_page.html';
alert("site_url" + site_url);
jQuery("#submit").click(function (event) {
alert("submit click" + jQuery("#submit").click);
window.location.href = site_url + "event-form";
});
// go to home.html
}
else {
alert('not valid!'); // alert not valid!
}
});

Jquery contact form sends multiple times

I'm trying to create a jquery contact form that sends an ajax request when clicked.
You can view it by visiting: http://childrensplaza.mn, and clicking the "click here to contact us button"
When testing this out though, After I click "send inquiry", it takes a while for the success message to show up, and I'm able to click it multiple times, causing my message to be sent multiple times.
The code for it is below ->
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
How would I make it so that the success message shows up on the first click, and I am not able to send the same request multiple times?
This is easy enough to handle by adding a class when submitted the first time, and checking if the class is applied to determine whether or not to process the form. If the button already has the class, do not continue to process.
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
Embedded in your code:
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
You could take one step further by resetting the class after successful ajax response.
$('#success').fadeIn(500); $("#submit").removeClass("pressed");
you can create a flag and control it with the ajax events beforeSend and complete ...
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
beforeSend: function(xhr, opts){
if($('#submit').hasClass("posting"))
xhr.abort();
else
$('#submit').addClass("posting");
},
complete: function(){
$('#submit').removeClass("posting");
},
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>

Java Script / AJAX email check function integration

I have a form with JS functions for checking empty fields and submit form without refreshing all page, I'm looking for a way to integrate email check function into what I'm having now:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#EBEBEB"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
}
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("textarea#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("textarea#phone").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Email sent</h2>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Thanks for help.
To check an email, you can use:
var emailReg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
function isEmail(email) {
return emailReg.test(email);
}
//call isEmail wherever you need it
If I may comment further on your code, I would recommend you cache your selectors and reuse them:
var input = $('input.text-input');
input.css({backgroundColor:"#EBEBEB"}).focus(function() //... and so on
Also, if your DOM is correctly structured, you do not have to call your ids with input selectors, it just slows down your implementation because its iterating over every input in the DOM than just getting it directly. That means:
$("label#phone_error") // don't do this
$("#phone_error") // do this
Also, you can use a data object to pass to jquery, so rather than
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
Do this:
$.ajax(yoururl, {data:
{
name: name,
email: email,
phone: phone
}, // and so on

Categories

Resources