How to validate form both on submit and keyup - javascript

My form validates on keyup, but when I try to validate it on submit too I just can't think what to do.
This is my HTML:
<form action="#" method="post">
<section class="col">
<section class="row">
<label for="name">Name</label>
<input type="text" name="name" value="" id="name" class="field validate-field valid-name" />
</section>
<section class="row">
<label for="email">Email Address</label>
<input type="text" name="email" value="" id="email" class="field validate-field valid-mail" />
</section>
<section class="row">
<label for="phone">Phone Number</label>
<input type="text" name="phone" value="" id="phone" class="field validate-field valid-phone" />
</section>
</section>
<section class="col">
<label for="message">Message</label>
<textarea class="field validate-field valid-text" name="message" id="message-field"></textarea>
<input type="submit" value="Submit" class="submit-button" />
</section>
</form>
JS:
function validate( field ){
var value = field.val();
var to_label = field.parent().find('label');
var error = false;
var error_message = '';
to_label.find('span').remove();
if ( field.hasClass('validate-field') && value == '' ) {
error = true;
error_message = 'Empty Field';
} else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
error = true;
error_message = 'Name must consist characters only';
} else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
error = true;
error_message = 'Invalid Email';
} else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
error = true;
error_message = 'Your phone must be digits only';
};
if ( error == true ) {
to_label.append('<span>'+ error_message +'</span>');
}
};
$('.validate-field').live('keyup', function(){
validate( $(this) );
});
function valid_name(value){
var valid = /^([a-zA-Z_\.\-\+])+$/;
return valid.test(value);
};
function valid_email(value){
var valid = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return valid.test(value);
};
function valid_phone(value){
var valid = /^[0-9-+]+$/;
return valid.test(value);
};
And I have to add something like this:
$('form').live('submit', function(){
if ( "...validated..." ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
What should be in the submit function?
I have tried:
$('form').live('submit', function(){
var valid = validate( $('.field') )
if ( valid == true ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
But this validates all the forms with all the validation (e-mail, phone ...). I have tried in validation() function to add if (error == false){ return: true }, then in submit function ran validation() and added if ( validation() == true ){ .. to send php ..}. That didn't work too. What I need to do ?

I guess you can validate the whole form by:
function validateAll() {
var valid = true;
$('form').find('.validate-field').each(function (i, e) {
if (!validate($(this))) {
valid = false;
return;
}
});
return valid;
}
function validate( field ){
var value = field.val();
var to_label = field.parent().find('label');
var error = false;
var error_message = '';
to_label.find('span').remove();
if ( field.hasClass('validate-field') && value == '' ) {
error = true;
error_message = 'Empty Field';
} else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
error = true;
error_message = 'Name must consist characters only';
} else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
error = true;
error_message = 'Invalid Email';
} else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
error = true;
error_message = 'Your phone must be digits only';
};
if (error) {
to_label.append('<span>'+ error_message +'</span>');
}
return !error;
};
$('form').live('submit', function(){
if (validateAll()) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
That's the option which requires the smallest amount of refactoring, on my opinion.
Just let me explain you what the function validateAll does. It finds all fields with class validate-field and pass it as argument to the validate function. Because of the refactoring I made in validate it returns false if the field is not valid so when we call validate with specific input and it's invalid we just return false (the form is not valid).
Here is an example in JSfiddle.
For more advance validation I can recommend you validation plugins like: http://docs.jquery.com/Plugins/Validation or jqxValidator.

You are almost done. Just add below code, it'll work
$('form').submit(function(){
var field = $(this).find('.validate-field');
validate( field );
});
Hope this will solve your issue.
Fiddle: http://jsfiddle.net/r1webs/cFeCx/

Related

Using the outcome of a function in another function [duplicate]

This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed last year.
I have created 3 functions to cilentside validate a form for its name, email, and website, I would like to create a 4th function that checks if the outcome of the 3 first functions is true, we submit the form, if the outcome of any of them is false, the form doesn't get submitted. Below is my attempt for the JavaScript.
The purpose of this question is to learn how to use a 4th function to check the other 3 functions returns.
//validating name, email, website:
function nameValidation() {
var valid = true;
var name = document.getElementById("name1").value;
var validname = /^[a-zA-Z\s]*$/;
if (name == "") {
document.getElementById("errorMsg2").innerHTML = "* Name is required";
valid = false;
} else if (name.match(validname)) {
valid = true;
} else {
document.getElementById("errorMsg2").innerHTML = "* Only letters and white spaces allowed";
valid = false;
}
return valid;
}
function emailValidation() {
var valid = true;
var validEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var email = document.getElementById("email1").value;
if (email == "") {
document.getElementById("errorMsg3").innerHTML = "* Email is required";
valid = false;
} else if (email.match(validEmail)) {
valid = true;
} else {
document.getElementById("errorMsg3").innerHTML = "*Please enter a valid email.";
valid = false;
}
return valid;
}
function websiteValidation() {
var valid = true;
var validWebsite = /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i;
var website = document.getElementById("website1").value;
if (website == "" || website.match(validWebsite)) {
valid = true;
} else {
document.getElementById("errorMsg4").innerHTML = "* Website is required";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit() {
if (nameValidation() == true && emailValidation() == true && websiteValidation() == true) {
return true;
} else {
return false;
}
}
document.getElementById("submit").addEventListener("click", () => {
console.log("Final result:", formSubmit());
});
<div>
<div id="errorMsg2"></div>
<input type="text" id="name1" />
</div>
<div>
<div id="errorMsg3"></div>
<input type="text" id="email1" />
</div>
<div>
<div id="errorMsg4"></div>
<input type="text" id="website1" />
</div>
<div>
<input type="submit" id="submit" />
</div>
Delete all of the JavaScript. This is the only HTML you need:
<input type="text" id="name1" pattern="[a-zA-Z\s]+" title="Letters and spaces only" required />
<input type="email" id="email1" required />
<input type="url" id="website1" required />
<input type="submit" id="submit" />
HTML5 Form validation has been around for a very long time at this point.

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Two fields validation

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" onsubmit="return validate();" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<input type="text" id="course_desc" name="course_desc" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_desc();">
<label id="course_desc_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate_course_desc(){
var TCode = document.getElementById('course_desc').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate(){
return validate_course_name();
return validate_course_desc();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on two field but the problem is if i give first input field valid input and second invalid form get submitted where am i doing it wrong? ...i am very new to this web so any help will be appreciated:)
UPDATED ANSWER:
Fine! Just to be different =)
One line, should validate both fields regardless if the validate_course_name() returns false.
JSFiddle: http://jsfiddle.net/fVqTY/3/
function validate()
{
return (validate_course_name() * validate_course_desc()) == true;
}
Let false = 0, true = 1. Now do the math :)
function validate(){
var value1 = validate_course_name();
var value2 = validate_course_desc();
if(value1 == true && value2 == true)
return true;
else
return false
}
or You can use
function validate(){
var validate = true;
var TCode = document.getElementById('course_name').value;
var TCode1 = document.getElementById('course_desc').value;
if(! /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
if(! /[^a-zA-Z1-9 _-]/.test( TCode1 ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
return validate;
}
and then call this function directly
In this function, You should return only once. So what happens here is that when validate_course_name() gets executed, control is already returned to the calling routine. validate_course_desc() line won't execute.
function validate(){
return validate_course_name();
return validate_course_desc();
}
You should do this:
function validate(){
var bol1 = validate_course_name();
var bol2 = validate_course_desc();
if(bol1 == true && bol2 == true)
return true;
else
return false;
}
Your validate method as given below will return as soon as the first validate method (validate_course_name) is called so it will not execute the validate_course_desc method.
function validate(){
return validate_course_name();
return validate_course_desc();
}
The solution is to execute both the validate method and summarise them to create the return value as given in the above answers
change the function validate()
function validate()
{
if(validate_course_name() && validate_course_desc())
{
return true;
}
return false;
}
Once return statement is executed in a function, other statements that are following return statement does not work.
Therefore every time, validate_course_name() function is called , a bool value is returned and the function validate_course_desc() is not even called/executed.
Therefore, the validate function returns true if validate_course_name() is true and false if validate_course_name() return false.Hence , When you give first field valid input and second invalid, form get submitted.
the validation of both inputfields is the same, so you can make one validation function which takes an element-id as parameter:
function validateInputfield(id){
var TCode = document.getElementById(id).value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById(id).innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
return true;
}
}
Then you can use the function validate() to check if both inputfields are valid:
function validate() {
if (validateInputfield('course_desc_info') == true &&
validateInputfield('course_name_info') == true) {
return true;
} else {
return false;
}
}

Javascript Coding in HTML

For an assignment I have I am writing a registration form. My question is how would I connect the first statement, and the function below so when someone types in their email in the text box it checks to see if the email is valid? (document.getElementById('user').value)
<input id="user" type="text" onblur="isUserNameValid();"></input><br/>
function isEmailValid(email) {
"use strict";
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[\w.-]/;
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
As you confirmed you can use HTML5, simply change your input to the below and the browser will validate the email for you when the form is submitted.
<input id="user" name="user" type="email" /><br/>
N.B. You can use a self closing tag for an input. You should also assign the name attribute of the input as that is what is used as the key for the data when it is submitted to the server.
<input type="text" id="email" name="email" onblur="javascript:return validate();"/>
<script>
function validate() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById("email").value;
if (reg.test(address) == false) {
alert('Invalid Email Address');
return false;
} else {
alert('valid Email Address');
return false;
}
}
</script>

HTML Form Validation via Javascript

I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami
Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>
try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});
Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.
If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>​
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});​
CSS
.error {
border: 2px solid red;
}​

Categories

Resources