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.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
This is my javascript but it works fine with all the other fields when nothing is entered I'm trying to make the user need to enter at least 8 characters before submitting but currently, they can submit on 0.
function validateForm() {
if (document.register.firstName.value == "") {
alert("Please provide your first name!");
document.register.firstName.focus();
return false;
}
if (document.register.secondName.value == "") {
alert("Please provide your second name!");
document.register.secondName.focus();
return false;
}
if (document.register.email.value == "") {
alert("Please provide your Email!");
document.register.email.focus();
return false;
}
if (document.register.phoneNo.value == "") {
alert("Please provide your Phone Number!");
document.register.phoneNo.focus();
return false;
}
if (document.register.Gender.value == "") {
alert("Must select a Gender!");
document.register.Gender.focus();
return false;
}
if (document.register.Terms.value == "") {
alert("Terms and Conditions must be accpeted");
document.register.Terms.focus();
return false;
}
if (document.register.psw.value.length > 7) {
alert("Password must contain 8 character");
document.register.psw.focus();
return false;
}
return (true);
}
You need to check if it's <= 7 characters in length (or probably < 8 for clarity). Currently you're preventing the user from submitting a password if it's too long, not the other way around:
if (document.register.psw.value.length < 8) {
...
}
I'm assuming you're using the password input field. If so, you can handle that from the HTML by doing something like this (see below) and have the browser handle the validation.
<input type="password" minlength="4" maxlength="8">
Just try the following. Notice, as you mentioned, it is not greater than 7, but less than 8.
if( document.register.psw.value.length < 8) {
alert( "Password must contain 8 character" );
document.register.psw.focus() ;
return false;
}
New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.
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 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>
I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}