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>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to validate a part of my form which is the postcode based on Malaysia's postcode which is a 5 digit numeric postcode. How to validate a value enter by user which has exactly 5 numbers only no more and no less? Thanks in advance!
Here's my part of the code:
HTML:
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Javascript:
function chkPostcode () {
var postcode = document.getElementById("postcode").value;
var pattern = /^[0-9]+$/; //check only alpha characters or space
var postcodeOK = true;
if ((postcode.length < 5 && postcode.length > 5)){ //same as owner==""
gErrorMsg = gErrorMsg + "Please enter postcode.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(postcode)){
gErrorMsg = gErrorMsg + "Postcode must only contain numbers.\n"
postcodeOK = false; //if condition or clause complex more readable if branches on separate lines
}
}
//if (!nameOk){
// document.getElementById("owner").style.borderColor = "red";
//
return postcodeOK;
}
This is a much shorter code for what you're trying to accomplish.
document.getElementById("postcode").addEventListener("input", function(e) {
if ( /^\d{5}$/.test(e.target.value)){
console.log("valid");
return;
}
console.log("invalid");
})
<label>Postcode: <input type="text" name="postcode" id="postcode" required="required"></label><br />
Your JavaScript is unnecessarily complicated. Here's a sure (and much better) way (except for all the ifs) to do this (the button and the check function are just for demo purposes):
function chkPostcode() {
var postcode = document.getElementById("postcode").value;
if(postcode.length !== 5)
{
return false;
}
else {
if(!isNaN(parseInt(postcode.charAt(0)))) {
if(!isNaN(parseInt(postcode.charAt(1)))) {
if(!isNaN(parseInt(postcode.charAt(2)))) {
if(!isNaN(parseInt(postcode.charAt(3)))) {
if(!isNaN(parseInt(postcode.charAt(4)))) {
return true;
}
}
}
}
}
}
return false;
}
function check() {
if(chkPostcode()) alert("Valid!");
else alert("Not a postcode");
}
<input type="text" id="postcode" />
<button onclick="check()">Check</button>
Just keep in mind, although client side (JavaScript) validation scripts are helpful, it's easy to defeat client-side JavaScript. Make sure you make some validation on the server-side as well, where the client can't tamper with the code as easily.
I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I enter 0900 in this text field then I would like it to automatically turn into 09:00
form
<form action="form.html">
<p>
<label>time:</label>
<input type="text" name="time" class="time"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
I Know I should use the following to at least get the value and then I have to turn that value into the value that I want:
$(document).ready(function(){
$(".time").on("focusout",function(){
var old_value = $(this).val();
// The old value to the new value
if(old_value.length < 2 || > 4){
$("#error").show();
} else {
if(old_value.length == 2){
// Then add 2 leading zero's
// Then add a : in the middle
} else if (old_value.length == 3){
// Then add 1 leading zero's
// Then add a : in the middle
} else if (old_value.length == 4){
// Then add a : in the middle
}
}
}
Thanks in advance for the effort taken. If something isn't clear please ask me.
Use this as a basis to solve your problem:
$("#your_filed_id").on("focusout", function(){
// Do whatever checking you like here
});
You can do like this:
JsFiddle: http://jsfiddle.net/ha9kx/1/
HTML:
<form action="demo_form.html">
<p>
<label>Hour:</label>
<input type="text" name="hour" class="hour_modification"/>
</p>
<span id="error" class="hide">Error in the field</span>
</form>
JavaScript:
$(document).ready(function(){
$(".hour_modification").on("focusout",function(){
var old_val = $(this).val();
if (old_val.length > 4 || old_val.length < 3){
$("#error").show();
}
else{
if(old_val.length = 3){old_val = "0" + old_val;}
var new_val = old_val.substring(0,old_val.length-2) + ":" + old_val.substring(old_val.length-2);
$(this).val(new_val);
}
});
});
This solution will work even if the user put "300" for "03:00"
If the entered value is always going to be 4 characters in the format you specified above, the following code should work. I don't use jQuery that often, but the following should give you an idea of what is required. You can modify the event listener with jQuery along with the selector.
http://jsfiddle.net/DS92Z/
<input type="text" id="time" />
<script>
var input = document.getElementById('time');
input.addEventListener('blur',function(e) {
var target = e.target || e.srcElement;
var value = target.value;
if(value.length != 4) {
return false;
}
target.value = value[0]+value[1]+':'+value[2]+value[3];
},false);
</script>
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.
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..