Javascript disable space key for change password textboxes - javascript

,Hi all,
var veri = {
YeniSifreTextBox: $('#YeniSifreTextBox_I').val(),
YeniSifreTekrarTextBox: $('#YeniSifreTekrarTextBox_I').val(),
};
if (veri.YeniSifreTextBox == '' || veri.YeniSifreTekrarTextBox == '') {
alert("Password Can not be empty!");
}
else if (veri.YeniSifreTextBox != veri.YeniSifreTekrarTextBox) {
alert("Passwords dont not match !");
}
I can control password can not be empty and passwords dont not match with above codes.
I want to disable to enter space key while user write password.
User must never use space in keyboard inside of 2 textboxes.
1.textbox YeniSifreTextBox_I
2.textbox YeniSifreTekrarTextBox_I

You can use the below javaScript code to block the space key,
function RestrictSpace() {
if (event.keyCode == 32) {
return false;
}
}
HTML
<textarea onkeypress="return RestrictSpace()"></textarea>
Hope this helps you.

<input type="number"
id="cardNumber"
name="cardNumber"
required
onKeyDown="if(event.keyCode === 32)
return false;">
You can implement the same functionality, without creating a custom function.

Related

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Password validation is not working in the login form

Password validation is not working in the login form. Here is my code:
function verifyPassword() {
var str = document.getElementById("t1").value;
if (str.match(/[a-z]/g) &&
str.match(/[A-Z]/g) &&
str.match(/[0-9]/g) &&
str.match(/[^a-zA-Z\d]/g) &&
str.length >= 8)
return true;
else
return false;
}
You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.
document.getElementById('t1').addEventListener('change', function() {
if (!verifyPassword()) {
alert("Invalid password");
}
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
if (!verifyPassword()) {
event.preventDefault();
alert("Invalid password");
}
}
Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.
The syntax ?=.*[x] means that you must have the condition x in your string.
Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.
function verifyPassword() {
var str = document.getElementById("t1").value;
var regEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");
if (regEx.test(str) &&
str.length >= 8)
console.log("good")
else
console.log("bad")
}
<div class="txt_field">
<input type="password" id="t1" value="" required>
<label>Password</label>
<button onclick="verifyPassword()">Verify</button>
</div>

Chrome Alert Box Submits Page Even if Returning False

In my application I have a textbox to search for items. In this textbox I want the user to have to enter at least 2 characters before searching. If there's less than 2 characters then I want to display a simple alert box telling the user to enter at least 2 characters. On my text box code looks like:
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
alert('Please ENter at Least 2 Characters');
//return false;
obj.select();
obj.focus();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" name="txtSearch" />
In my javascript the function on every keystroke from the user, it checks the keyCode being pressed looking for the 'Enter' input. If the user presses 'Enter' and the number of characters in the textbox is less than 2 then it should alert the user and return false. But regardless the form is still submitted when the user presses 'Enter'.I also noticed it doesn't hit the 'doEnterKey' function it just submits the form. Any help or suggestions is appreciated.
In Internet Explorer everything works as should, the javascript code stops wait for input from the user then continues, returning false. However in chrome the alert box is displayed it and it still submits the form, almost as if it's not returning the false back to the element.
Pass the event object in the call and on ENTER prevent event default.
I used the keypress event and tested on IE, FF and Chrome.
Now the alert message on form submit will not happen because the ENTER is prevented.
function checkSearchLen(event, obj, defaultEnterButton) {
event = event || window.event;
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
event.preventDefault();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<form action="http://www.google.com" onsubmit="alert('submit');">
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeypress="checkSearchLen(event, this,'MenuBar_imgSearchGo');" name="txtSearch" />
</form>
The best method to deal with this kind of problems is by using Jquery...just a few lines of Jquery code is capable of doing what you did in the entire program!
Another alternate answer is to do checking in form submit event and cancel that submit event based on invalid input. This will prevent page post back. Actually, this is the same approach that ASP.Net framework takes when a page has ASP.Net validators in it with client-side validation turned on.
Also, there is no need to cancel the event in doEnterKey, so I have commented two lines in that function.
The following code will work as I have tested on my side. There are two aspects to the logic being used:
A global variable stopSubmit decides if form submit event will be canceled or not. If this variable is true then form submit event will cancel.
The original form submit event code of the form is being pre-pended with our custom JavaScript that will return a false in case the form submit needs to be canceled. This is happening when body loads for the page i.e. body's onload event calls setFormSubmit to modify existing form submit code. If everything was valid, then original form submit code executes without issues and page posts back.
<body onload="setFormSubmit()">
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server"></asp:Label>
<div>
First name:
<input type="text" name="FirstName" value="Mickey" /><br />
Last name:
<input type="text" name="LastName" value="Mouse" /><br />
<input type="submit" value="Submit" />
<input type="text" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" />
<input type="submit" value="Submit" id="MenuBar_imgSearchGo"/>
</div>
<script>
var stopSubmit = false;
function setFormSubmit() {
document.forms[0].setAttribute("onsubmit", " var stopPostback = StopPostback(); if(stopPostback === true) { return false; } " + (document.forms[0].onsubmit === null ? "" : document.forms[0].onsubmit));
}
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value === 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
stopSubmit = true;
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
return false;
} else {
stopSubmit = false;
doEnterKey(defaultEnterButton);
}
}
function doEnterKey(s) {
if (event.keyCode == 13) {
//event.returnValue = false;
//event.cancel = true;
document.getElementById(s).click();
}
}
function StopPostback() {
if (stopSubmit === true) {
stopSubmit = false;
return true;
}
return false;
}
</script>
</form>

Trying to validate form field with jQuery

I know I must be missing something super simple here, because in theory this code is supposed to work, but it's not, and I cannot understand why. I'm trying to work out my own jQuery form validation, because I tried the jQuery form validator plug-in, and while setting up the rules and messages is perfectly simple, figuring out how to get the error message to show up where I wanted it to was a nightmare (couldn't get the message to show up AFTER radio buttons, for example.)
I've got the 1st part of my attempted validation working, but I can't clear the message once you enter something in the field. Also, the message pops up even when conditions are met, which doesn't make sense to me.
here's the jsfiddle
html
<form>
<p>
<lable for="name">Enter your name:</lable>
<input type="text" id="name" name="name">
<span class="error"></span>
</p>
<lable for="age">Enter your Age:</lable>
<input type="text" id="age" name="age" width="3">
<span class="error"></span>
</p>
</form>
jQuery
$("input").focusin(function(){//highlight input field on focus
$(this).css("background-color", "yellow");
});
$("input").focusout(function(){
$(this).css("background-color", "white");
});
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this))){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
$("#name").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this)) != false){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
$("#age").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
You forgot the $(this).val()
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this).val())){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
and again at age
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this).val())){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
also you can remove != false - e.g
if (test != false)
is the same as
if (test)
Heres the fixed up fiddle
Need to Remember Some thing while validating form Using JS:-
Check input value Using (this).val();
if Error Occur then forward to next vale with Error .
Check test value is false or true using if (test != false) or if (test)
then forward your Control for success page
You can use the lettersonly rule.
Here's an example:
Define a variable validator and do this :
validator = $("form").validate({
rules: {
name: { required: true,
lettersonly: true
}
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
you need to call
$("form").valid()
and if it is valid means without any errors then do :
validator.hideErrors();
$("form" div.has-error").removeClass("has-error");
For age input for numeric only jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Categories

Resources