JS validation issue - javascript

My validation function looks like that.
var fname = $("#fname").val();
var lname = $("#lname").val();
function validate() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid=false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid=false;
}
It simply changes the class of unfilled input box.
I know that i can write else for every if and change back to default (class="valid") if user fills some of inputs. But how can i create something universal for all inputs to change back to default class the input that user has filled after first validation error?

That was good Tural! HOWEVER, why the excess processing in your code? That will add unecessary stress. Since you, for what you "solved", will add the "valid" class to ALL the input type text or password, just add that to the actual input element in the straight code:
<input class='valid' ..... />
Now, back to your original validation: why not make it universal?:
function validate(formField) {
if !formField $('#'+formField).removeClass('valid').addClass('invalid');
}
Or something in that vein ...

You can either assume everything is valid and then try to disprove that or you can try to prove its validity. The below takes the first approach and sets all the classes to "valid" to be consistent with that.
function validate() {
// Get the current form input state.
var fname = $("#fname");
var lname = $("#lname");
// Assume everything valid until proven otherwise.
var isValid = true;
fname.attr('class', 'valid');
lname.attr('class', 'valid');
if (!fname.val()) {
fname.attr('class', 'invalid');
isValid=false;
}
if (!lname.val()) {
lname.attr('class', 'invalid');
isValid=false;
}
return isValid;
}

Ok. I found the way
$('input[type="text"],input[type="password"]').keypress(function () {
$(this).attr('class', 'valid');
});

Related

How can I validate user input (characters and number) with javascript?

From this example
I tried to validate user input when a button was clicked.
$("#check_data").click(function () {
var $userInput = $('#user_input'); //from HTML input box id="user_input"
var pattern = " /*My user input always be like "AB1234567"*/ ";
if ($userInput.val() == '' || !pattern.test($userInput.val())) {
alert('Please enter a valid code.');
return false;
}
});
My user input input always be like "AB1234567" with this exact same characters but different 7 digits number.
I'm new to Javascript and Jquery, if you have any better way to validate user input, please suggest it.
Thank you.
You can use below regex Expression to check
/[A-Za-z0-9]/g
Your code could be like this
var _pattern=/[A-Za-z0-9]/g
if($userInput.val().match(_pattern))
{
//your code goes here..
}
Thanks
You can use the below pattern to check
/^AB\d{7}$/
You can change code to
var pattern = '/^AB\d{7}$/';
if ($userInput.val() == '' || !pattern.test($userInput.val()))
{
alert('Please enter a valid code.');
return false;
}
\d{7} matches 7 digits in the range [0-9]
You can follow below code for this:
if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
// it is a valid value.
} else {
// show error here
}
Hope it helps you.
Try this one.
$("#check_data").click(function(){
var $userInput = $('#user_input').val();
var pattern = /^AB[0-9]{7}?/g;
if(!$userInput.match(pattern)){
alert('Please enter a valid code.');
return false;
}
});

Having difficulty getting Javascript form to validate

Been looking for an answer for hours now and I still haven't come up with a solution. I've tried looking for similar question, but none have helped, really.
So basically, what doesn't work is that the form submits without any error messages even if there are mistakes on the form. Basically, I could leave the name field empty and the form will still submit once I press the button. Hope this made sense. Any help is appreciated
Code:
function validateFinale()
{
var emailOne = document.getElementById("em1").value;
var emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
if (compare())
{
if (name, 'Please enter name'))
{
if (validEmail(getElementById('em1'), 'Email invalid'))
{
}
}
}
return false;
}
function validName(elem, helpmsg) {
if (elem.value.length == 0) {
alert(helpmsg);
return false;
} else {
return true;
}
}
function validEmail(elem, msg) {
var wrongem = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]+$/;
if (elem.value.match(wrongem)) {
return true;
} else {
alert(msg);
return false;
}
}
function compare() {
if (emailOne != emailTwo) {
alert("Emails not the same");
submitOk = "false";
Document.getElementById("em1").value = " ";
Document.getElementById("em2").value = " ";
Document.getElementById("em1").focus();
} else {
alert("form complete, thank you");
}
}
http://jsfiddle.net/aj240/qgmt5yr8/
you made syntax mistake, first you declare emailOne as local variable, than try reach it in global scope. You should declare variables emailOne and emailTwo in global scope.
var emailOne;
var emailTwo;
function validateFinale()
{
emailOne = document.getElementById("em1").value;
emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
One gold tip, try press F12 in your browser and all errors messages would appear in console.
Try setting required ="true" in the input elems:
<input type="text" required ="true"...
Also, if you set type="email" in the e-mail field it will ask for an e-mail address (not at all, though, it just will accept anything with an "#")
And the code validName(getElementById('name1'), ...) should be validName(getElementById('name1').value, ...), or else you'll get all the HTML element

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

JQuery Append only working once

Trying to load a custom form submisson error box in Facebox, when testing around with some code im having trouble getting .append() to append more than one time. If both of the example errors are failed its only loading appending and loading one in to the facebox, but if one at a time is failed it will show the correct one that is supposed to display, just not both at once..
Sorry if the code is messy / not efficient, javascript isn't my strong suit.
$('#signup').submit( function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var uname = $("#username").val();
var pass = $("#password").val();
var passc = $("#passwordc").val();
var email = $("#email").val();
if(/^[a-zA-Z0-9_]*$/.test(uname) == false) {
//alert('Usernames can be alphanumeric but may include an underscore.');
$("#errorholder").append('<tr><td style="margin: 0;">Usernames can be alphanumeric but may include a underscore.</td></tr>');
}
else if(/^[a-zA-Z']*$/.test(fname) == false) {
//alert('First name may not contain numbers or symbols.');
$("#errorholder").append('<tr><td style="margin: 0;">First name may not contain numbers or symbols</td></tr>');
}
else if(/^[a-zA-Z']*$/.test(lname) == false) {
//alert('Last name may not contain numbers or symbols.');
}
else if(!$("#fname").val()){
//alert('First name required');
}
else if(!lname){
//alert('Last name required');
}
else if(!uname){
//alert('Userame required');
}
else if(pass!=passc){
//alert('Passwords don\'t match');
}
else if(pass.length<5){
//alert('Password must be at least 5 characters.');
}
else if(!email){
//alert('Email required');
}
else if (!$("input:radio[name='gender']:checked").val()) {
// alert('Please select gender.');
}
jQuery.facebox({ div: '#piksplay' });
return false;
});
});
You're trying to test multiple conditions, but you're using else if. As soon as your code find a true condition then it doesn't test anything else, so only one append will get fired each time. These all need to be separate if statements.

Categories

Resources