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

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;
}

Related

Javascript show validation message right after the text box

I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}

How to change the value of an active text input using Javascript?

I am trying to make a form with a date input.
However, this input is in date format, and I would like to change the value while the control is still active.
Here is the full code :
// Javascript code
function add_value()
{
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length = 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length = 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onchange="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
But this is only updating the text when you exit of the control, and I would like to know how to run this javascript function while the control is still active.
Thanks.
You need to use onkeyup.
<input id="fin_mater" type="text" onkeyup="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
From the docs
Execute a JavaScript when a user releases a key
Also in your if your are using =, you should be using ==
...
if(document.getElementById("fin_mater").value.length == 2)//==
...
else if(document.getElementById("fin_mater").value.length == 5)
...
First let's make the code smell more like the "javascript" :)
// Javascript code
function $(id) {
return document.getElementById(id);
}
function add_value(event) {
var dataOriginale = $("fin_mater").value,
len = dataOriginale.length,
key = event.keyCode || event.charCode;
// Allow BACKSPACE and DEL
if (key === 8 || key === 46) {
return true;
}
if(len === 2 || len === 5) {
$("fin_mater").value = dataOriginale + '-';
}
return false;
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onKeyUp="add_value(event);" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
If you want to append the "-" automatically when you input numbers, you can listen on the "onKeyUp" event of the text box rather than the "onchange".
PS: You can use the key code to limit only numbers input and also do some validations.
You can use keypress():
$(document).ready(function()
{
$( "#fin_mater" ).keypress(function() {
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
});
});
Fiddle
With some of your help and some documentation, I finally went to this, that works perfectly on every browser that supports javascript.
$(document).ready(function(event)
{
$( "#fin_mater" ).keypress(function(event) {
var dataoriginale = document.getElementById("fin_mater").value;
if(event.keyCode != 8)
{
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
});
});
Thanks everyone !

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]);
}

Swap default field value using pure 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

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