Swap default field value using pure JavaScript - javascript

I've written some code in jQuery for removing/replacing the default value of an e-mail field on focus and blur events. Its' working fine,
But I wanted it in JavaScript .. I've tried several times but I couldn't succeed.
here's my jQuery Code
$(document).ready(function(){
var email = 'Enter E-Mail Address....';
$('input[type="email"]').attr('value',email).focus(function(){
if($(this).val()==email){
$(this).attr('value','');
}
}).blur(function(){
if($(this).val()==''){
$(this).attr('value',email);
}
});
});
can anyone tell me how to do it in JavaScript,

Assuming <input type='text' id="email_field"/>
var email = 'Enter E-Mail Address....';
var emailField = document.getElementById("email_field");
emailField.onfocus = function(){
removeDefaultText(this);
}
emailField.onblur = function(){
setDefaultText(this);
}
function removeDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == defaultValue){
element.value = "";
}
}
function setDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == ''){
element.value = defaultValue;
}
}

Apparently you're trying to display a placeholder value, when there is no other value.
In any modern browser, you might simply use this:
<input type="text" class="email" placeholder="Enter E-Mail Address..." />
Unfortunately that excludes older IEs, so an approach for vanilla JavaScript could be like this:
// grab all input[type="email"] elements
var emailFields = document.getElementsByTagName('INPUT').filter(function(input) {
return input.type === 'email';
});
var placeholder = 'Enter your E-Mail Address...';
// watch onfocus and onblur on each of them
emailFields.forEach(function(input) {
input.onfocus = function() {
// clear only if the value is our placeholder
if (input.value === placeholder) {
input.value = '';
}
}
input.onblur = function() {
// set the value back to the placeholder, if it's empty
if (input.value === '') {
input.value = placeholder;
}
}
});
Hope that suits your needs.

try
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}
with jQuery
var userinputmail= $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinputmail))
{
alert('not a valid e-mail ');
}​
You can also try the following regex for other validation (I think this will helpful)
Matching a Username => /^[a-z0-9_-]{3,16}$/
Matching a Password => /^[a-z0-9_-]{6,18}$/
Matching a URL => /^[a-z0-9_-]{6,18}$/

You can use regular old javascript for that:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
======
using new regex
demo http://bit.ly/Hzbq4i
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\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);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex
email check exists!
check this link

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

loop through all fields and return false if validation of any one field fails jquery

I am facing big trouble resetting the flag variables. I am not sure where I am missing :(
I have a form with lots of text fields. I am trying to loop through all the fields and on blur of each of the field I am doing some validations. If any of the validation for any of the field fails it should not submit the form. But now I am having a big trouble doing this. If I have 3 fields and the first value I have entered wrong and next two fields if I have given correct, its submitting the form which should not be. Can somebody please help me in this?
var globalValid = false;
var validators = {
spacevalidation: function(val) {
if($.trim(val) != "")
return true;
else
return false;
},
//Other validation fns
};
$('#form1 .required').blur(function(){
var input = $(this);
var tmpValid = true;
input.each(function(){
var classReturn = true;
validatorFlag = true;
input.next('ul.innererrormessages').remove();
input.removeClass('required_IE');
if(firstTime)
{
input.addClass('valid');
}
if (!input.val()) {
input.removeClass('valid');
input.addClass('required');
var $msg = $(this).attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
globalValid = false;
}
else{
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
tmpValid = (tmpValid && validators[classes[p]] (input.val())) ? tmpValid : false;
}
}
}
if(tmpValid == false){
input.removeClass('valid');
input.addClass('required');
var $msg = input.attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
}
}
});
globalValid = tmpValid;
});
$('#form1').submit(function() {
var returnValue = true;
if(globalValid )
{
returnValue = true;
}
else{
returnValue = false;
}
alert("returnValue "+returnValue);
return returnValue;
});
Using this code, if I put a wrong value for first field and correct value for the other two fields, ideally it should return false. But its returning true. I think I am not properly resetting the flag properly
Checkout this example which provides the basic premise of what needs to occur. Each time the blur event is fired you must validate all three fields and store the result of their validation to a global variable.
HTML
<form>
<input />
<input />
<input />
<button type="submit">Submit</form>
</form>
Javascript
var globalValid = false; //Global validation flag
$("input").blur(function(){
//local validation flag
var tmpValid = true;
//When one input blurs validate all of them
$("input").each(function(){
//notice this conditional will shortcircuit if tmpValid is false
//this retains the state of the last validation check
//really simple validation here, required value less than 10
tmpValid = (tmpValid && this.value && this.value < 10) ? tmpValid:false;
});
//assign the result of validating all inputs to a global
globalValid = tmpValid;
});
$("form").submit(function(e){
//This is just here to make the fiddle work better
e.preventDefault();
//check the global validation flag when submitting
if(globalValid){
alert("submitted");
}else{
alert("submit prevented");
}
});
JS Fiddle: http://jsfiddle.net/uC3mW/1/
Hopefully you can apply the principles in this example to your code. The main difference is the code you have provided does not validate each input on blur.

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Categories

Resources