Can this jQuery validation be refactored? - javascript

I'm doing some simple client side validation with jQuery.
var passedValidation = new Boolean(true);
// Required Field Validators.
if ($('#fbsignup input.firstName').val().trim() == '') {
$('#fbsignup tr.firstName em').show();
passedValidation = false;
}
if ($('#fbsignup input.lastName').val().trim() == '') {
$('#fbsignup tr.lastName em').show();
passedValidation = false;
}
if ($('#fbsignup input.email').val().trim() == '') {
$('#fbsignup tr.email em').show();
passedValidation = false;
}
if ($('#fbsignup input.password').val().trim() == '') {
$('#fbsignup tr.password em').show();
passedValidation = false;
}
if ($('#fbsignup input.screenName').val().trim() == '') {
$('#fbsignup tr.screenName em').show();
passedValidation = false;
}
if (passedValidation == true) {
// All validation passed. Hide the modal signup dialog and post back to signup user.
$('#fbcSignupModal').jqmHide();
return true;
} else {
return false;
}
Essentially, i want to ensure all fields are filled in. If any aren't, return false, else return true. Simple.
Can this be refactored to a single line? (perhaps by applying a class to all elements?).
A caveat on the answer, i do NOT want to use the jquery-validate plugin. I know its awesome, but this is not very difficult validation and i do not want to affect the rest of the form (this is a modal popup).
So, that being said - any ideas?
EDIT
Just to clarify, i do need to know which field wan't filled in, so i can show an * next to it.
EDIT2
Updated the original code to indicate i need to show a required field label and return false if validation fails.
EDIT3
Okay i've rethought my solution, and it looks like i'll need to do a server-call to validate the email against the membership schema. So i'm probably going to end up either wrapping the fields in an update panel or doing a web service post (and return errors in a json array). However, i'll leave this question open for a while and pick the answer with the most votes.
ANSWER
So i've gone with a modified version of #box9's answer. I'll still need to do an AJAX call to the server to validate the email (as my edit above suggests), but this will ensure i only do that if all fields are filled in.
$('#fbsignup input.required').each(function (index) {
if ($(this).val().trim() == '') {
$(this).next('em').show();
passedValidation = false;
}
});
I have an em element directly after the input fields which are required, so i can easily use the .next([selector]) jQuery selector.
Nice and easy.
Thanks for all the answers.

The following code does exactly what your code does:
var passedValidation = true;
$('#fbsignup input').each(function(index) {
if ($(this).val().trim() == '') {
$('#fbsignup tr').filter('.' + $(this).attr('class').split(' ').slice(0, 1)).find('em').show();
passedValidation = false;
}
});
if (passedValidation) $('#fbcSignupModal').jqmHide();
return passedValidation;
... except for one caveat: it'll only work if the classes "firstName", "lastName", etc... are the FIRST class in the class attributes of your inputs. This limitation, and the convoluted line $('#fbsignup tr').filter('.' + $(this).attr('class').split(' ').slice(0, 1)).find('em').show();, only exists because I don't know the structure of your HTML. The selectors can be a lot cleaner (using .sibling(), .children(), .parent(), etc. if the HTML structure is known.
Alternatively, include an array of all the classnames of your inputs:
var inputClasses = ['firstName', 'lastName', 'email', 'password', 'screenName'];
And iterate through these:
var passedValidation = true;
$.each(inputClasses, function(index, className) {
if ($('#fbsignup').find('input.' + className).val().trim() == '') {
$('#fbsignup').find('tr.' + className + ' em').show();
passedValidation = false;
}
});
if (passedValidation) $('#fbcSignupModal').jqmHide();
return passedValidation;
The downside to this is that you'll have to manually update the array if you change/add inputs. Your best bet is probably to modify my first solution using the known structure of your HTML, or even convert classes to IDs.

function validate() {
var fields = ['firstName', 'lastName', 'email', 'password', 'screenName'];
for(fieldIdx in fields) {
if($('#fbsignup input.' + fields[fieldIdx]).val().trim()) == '' {
$('#fbsignup input.' + fields[fieldIdx]).after("*");
return false;
}
}
return true;
}
This does what you want, but has the disadvantage of losing information about which field it was that failed validation (if you wanted to pop up a field-specific message, for example).

Something like this should work for you.
var failedElements = $("#fbsignup input").filter(".firstname[value=''], .lastname[value=''], .email[value='']");
Here is an example:
http://jsfiddle.net/zfQbz/
EDIT: I just noticed you edited the question again. So if you want to take action against each item that failed just use a for loop to iterate all the items in the collection and do what you need for each one.

If you want to check that all fields are filled, just do:
function validate() {
ret = true;
$('#fbsignup input').each(function(index) {
if ($(this).val().trim()) == '') ret = false;
});
return ret;
}

I recommend you to use this jquery validation plugin , it's easy to use and powerful..

Related

Email validation doesn't capture with required fileds

I have a javascript validation function.I need to check if required fileds are empty or wrong mail address.Required fileds empty is working But when i type mail like abc#abc or something wrong then it doent catch the error in my code.
When i type all required fileds but wrong email address ( abc#abc or abc.com like doesn't capture.)
My Code
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') ||
($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
}
status = false;
}
Email Validate Function
function ValidateEmail(email) {
var expr = /^([\w-\.]+)##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
Your test for a valid email is inside the if block which test if the value is not null, so when you enter any value in the text box (whether its valid or not) the if (!ValidateEmail($("#txtemail").val())) { will never be called. Change your script to
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') || ($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
status = false;
} else if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
status = false;
}
}
Side note: All this functionality is provide out of the box in MVC by simply adding the [Required] and [EmailAddress] attribute to your property and including the relevant scripts (jquery.validate.js and jquery.validate.unobtrusive.js) and #Html.ValidationMessageFor() helpers which means you get both client and server side validation (and it's all done correctly!)

My condition checking is not properly work in JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to show an alert message when the check box is not selected. I use the following code for that purpose
function IsEmpty(){
var oldpath = document.forms['pathuploader'].oldpath.value;
var newpath = document.forms['pathuploader'].newpath.value;
var metavalue = !document.forms['pathuploader'].chkmeta.checked;
var postvalue = !document.forms['pathuploader'].chkpost.checked;
if((oldpath == "")||((oldpath.substring(0,4))!='http')||((oldpath.substring(0,4))=='Http'))
{
alert("Enter a valid URL");
return false;
}
if((newpath == "")||(newpath.substring(0,4)!='http')||(newath.substring(0,4)!='Http'))
{
alert("Enter a valid URL");
return false;
}
if((metavalue) && (postvalue))
{
alert("Select any category to change");
return false;
}
return true;
}
Working JSFiddle
First of all you have a typo on the following line
if((newpath == "")||(newpath.substring(0,4)!='http')||(newath.substring(0,4)!='Http'))
The last if is "newath" should be "newpath" and the same area "!=" should match the oldpath logic and instead be "==".
To clean up the code just a bit more, use "===" and "!==" instead of just "==" as this forces a more precise comparison.
See this link for more info use strict mode
Here is adjusted code
Also, try to use a camelCase naming convention if you wish to comply with JS standards. I have corrected the "IsEmpty" function to be "isEmpty" as an example.
function isEmpty(){
var oldpath = document.forms['pathuploader'].oldpath.value;
var newpath = document.forms['pathuploader'].newpath.value;
var metavalue = !document.forms['pathuploader'].chkmeta.checked;
var postvalue = !document.forms['pathuploader'].chkpost.checked;
if((oldpath === "")||((oldpath.substring(0,4))!=='http')||((oldpath.substring(0,4))==='Http'))
{
alert("Enter a valid old URL");
return false;
}
if((newpath === "")||(newpath.substring(0,4)!=='http')||(newpath.substring(0,4)==='Http')){
alert("Enter a valid new URL");
return false;
}
if((metavalue) && (postvalue)){
alert("Select any category to change");
return false;
}
return true;
}
UPDATE I also agree with "Sourabh" where the BANG (!) should be. As in
if(( !metavalue ) && ( !postvalue ){
instead of how it is currently. Both work, but the BANG is hiding in the variable. If you did keep it where it is, perhaps you could alert the next programmer that may view your code by calling it
var metaValueNotChecked = !document.forms...
var postValueNotChecked = !document.forms...
Then it would read correctly as
if(( metaValueNotChecked ) && ( postValueNotChecked ){
In this case, the BANG should be where you have it.
Hope this helps!
use the below procedure for more better way to do it, i am assuming that you have elements defined in your form, you need to change this two parts of code
first:
var metavalue = document.forms['pathuploader'].chkmeta.checked;
var postvalue = document.forms['pathuploader'].chkpost.checked;
then in if condition use the below procedure:
if(!metavalue && !postvalue)
{
alert("Select any category to change");
return false;
}
You can use "required" from HTML5, and remove it once a checkbox is checked, from every other of your checkbox. ex:
<input required="required" value="1" name="site[source][]" id="site_source_any" type="checkbox">
<input required="required" value="2" name="site[source][]" id="site_source_many" type="checkbox">
In your script file:
<script type="text/javascript">
// Check if atleast one of the checkbox is checked
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
// Remove Required once at-least one is checked
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
</script>

A short way of cheking multiple blank text fields jQuery

I need to check if there are blank input text fields in my < form >. Instead of doing this multiple times
$.trim($('#myMessage').val()) == '' || $.trim($('#myage').val()) == '' .//so on...
What is the best way to check multiple blank text fields?
use:
if($('input:text[value=""]').length);
try
$("form input[type=text]").filter(function () {
return $.trim(this.value) != "";
}).length;
Note: You have to use any form id or class instead of form
Here is the code ,
// Validate form fields in Sign up form
$(".signup-form").submit(function(){
var isFormValid = true;
$(".signup-form .required input:text").each(function(){ // Note the :text
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("highlight");
isFormValid = false;
} else {
$(this).parent().removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
return isFormValid;
});

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

JQuery Validation for Two Password Fields

Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
    $(".error").show(500);
}else{
 $(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.

Categories