Some simple form validation seems to require hitting Enter once the correct value has been added before allowing the visitor to move on. Any way to eliminate that? Here is an example of one of them.
// Makes sure that the email looks valid and contains an #, a . and at least two characters after the dot
function checkEMail(obj) {
var emailFilter = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (!emailFilter.test(obj)) {
obj.style.background = 'Yellow';
alert('Please enter a valid email address, then press Enter to continue.');
} else if (!illegalChars.test(obj)) {
obj.style.background = 'Yellow';
alert('The email address contains illegal characters.');
} else {
obj.style.background = 'White';
}
}
Just make a return to true in your "happy flow" in the validation function.
// Makes sure that the email looks valid and contains an #, a . and at least two characters after the dot
function checkEMail(obj) {
var emailFilter = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ ;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (!emailFilter.test(obj)) {
obj.style.background = 'Yellow';
alert('Please enter a valid email address, then press Enter to continue.');
} else if (!illegalChars.test(obj)) {
obj.style.background = 'Yellow';
alert('The email address contains illegal characters.');
} else {
obj.style.background = 'White';
return true;
}
}
Script with similar type of logic, working example:
function execute(a) {
if(a === 1) {
alert("1");
} else if (a === 2) {
alert("2");
} else {
console.log('lele');
return true;
}
}
execute(3);
Related
So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.
Can someone tell me why this function doesn't work? the password length and the check of number work perfectly. But it is something wrong with the check of big capitals...
function validera() {
var passw = document.getElementById("User-Password").value;
var upper = /[A-Z]/ ;
var number = /[0-9]/;
if (passw.length < 6 || !number.test(passw) || !upper.test(passw)) {
if (passw.length < 6) {
alert("Please make sure password is longer than 6 characters.")
return false;
}
var counter = 0;
var i;
for(i = 0; i < passw.length; i++){
passw.charAt(i)
if(upper.test(passw.charAt(i))){
counter++;
break;
}
}
if( counter < 2 ){
alert("Please make sure password includes 2 capital letters")
return false;
}
if (!number.test(passw)) {
alert("Please make sure Password Includes a Digit")
return false;
}
} else {
alert("Account created")
}
Or do I have to use regex?
If you are planning to use regex to find two capital letters then you can use like
\w*[A-Z]\w*[A-Z]\w*
Test this here on regextester
Here Check it out Fiddle
CreateRandomPassword(Length, isUpperAlpha, isLowerAlpha, isNumaric ,SpecialChars)
I have developed easy function to generate password
Here's a function that returns an object with a message and a boolean.
Example snippet:
function testPassword(pwd) {
if (pwd.length <= 6)
return { valid: false, message: "Please make sure password is longer than 6 characters." };
if(!/[A-Z].*[A-Z]/.test(pwd))
return { valid: false, message: "Please make sure password includes 2 capital letters" };
if (!/\d/.test(pwd))
return { valid: false, message: "Please make sure Password Includes a Digit" };
if (/\s/.test(pwd))
return { valid: false, message: "Please only use visible characters" };
return { valid: true, message: "Valid Password" };
}
console.log(testPassword('Val1dPassword'));
console.log(testPassword('SH0rt'));
console.log(testPassword('No2capitals'));
console.log(testPassword('NoDigits'));
console.log(testPassword('Has\tat least 1 WhiteSpace'));
Then your function can be simplified.
function validera() {
let passw = document.getElementById("User-Password").value;
let check = testPassword(passwd);
if (check.valid) {
alert(check.message);
return false;
}
else {
alert("Account created")
}
}
I have a simple program that validates a sign up form. Basically I reach a problem when one of my "if" statements can only execute the "else" part. If I change the form so that "if" is executed, nothing happens. Below is my code:
function verifyprocedure() {
var originalpassword = document.getElementById("password").value;
var checkpassword = document.getElementById("verifypassword").value;
var emailcheck = document.getElementById("email").value;
var male = document.getElementById("gendermale");
var female = document.getElementById("genderfemale");
var form = document.getElementById("signup");
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}
} else {
$("#verifypassword").notify("Passwords do not match.");
}
}
Did you check whether it is working or not ?
anyway it is working for me,i think your input should be invalid you can use the following code for checking
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
alert("hai");
}
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck))
{
alert("Hello World!");
} else {
alert("Please enter a valid email address.");
}
}
Working DEMO
UPDATE
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword)
{
alert("hai");
if (originalpassword.length > 9)
{
if (emailexist.test(emailcheck))
{
alert("Hello World!");
}
else
{
alert("Please enter a valid email address.");
}
}
else
{
alert("Passwords must have at least 9 characters.");
}
}
else {
alert("Passwords do not match.");
}
Check this DEMO It will satisfy all conditions.
Note : Check your if condition for password length, if you want the desired output then it will be like if (originalpassword.length > 9)
if (originalpassword.length > 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}
I have this javascript function:
if (myform.telephone.value.length < 10){
jAlert ('Please enter at least 10 characters!',function(){$(myform.telephone).focus();});
return false;
If the user enters less than 10 characters, an alert is triggered. I need to modify the script so that the alert pops if the user enters less than 10 DIGITS (0,1,2,etc)..
How can i do this ?
Update: As the OP correctly pointed out, there was a bug in the previous method. I advise not to use isNan as it is broken. I've updated the answer, code below.
This can be easily done by mathcing the input against a regular expression and then checking if the resulting number has 10 or more digits. Like:
var validate = function(){
var number = tryParseNumber(input.value);
if(number.toString().length < 10){
alert("Invalid input");
} else {
alert("Valid output: " + number);
}
};
var tryParseNumber = function (value) {
if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return false;
}
See this Fiddle for a working example.
Try :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
function phonenumber(inputtxt)
{
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following cod
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
I want to check if the password length is at least 8 characters or not, when the user leaves the password field or press tab key.
How can i do this?
My code for password is shown below.
<input type="password" name="password" id="pass1" placeholder="password"/>
Use the jquery blur method for this.
$('#pass1').on('blur', function(){
if(this.value.length < 8){ // checks the password value length
alert('You have entered less than 8 characters for password');
$(this).focus(); // focuses the current field.
return false; // stops the execution.
}
});
Fiddle for Demo
You can use javascript onchange event as below
and script code callfunction() as
function callfunction()
{
var textBox = document.getElementById("pass1");
var textLength = textBox.value.length;
if(textBox.value=='' || textLength<=8)
{
alert('Please enter correct password');
}
}
try this:
$('#pass1').on('blur', function(){
if($(this).val().length > 8){
alert('safe!');
}
});
here is an example: http://jsfiddle.net/ACK2f/
Password validation can use several rules, I used a service but the code inside the function can be reusable:
_validatePassword = function (validateUserNameRules, Model)
{
//bolean parameter validateUserNameRules -> true/false
//this method recive a model like this:
//Model.userName -> string
//Model.password -> string
//Model.password2 -> String
var validationResult = {
ResultId: 1, //1 success
Message: "Password is correct."
};
if (validateUserNameRules && Model.userName == "") {
validationResult.ResultId = 2;
validationResult.Message = "Error: User name cannot be blank.";
return (validationResult);
}
var re = /^\w+$/;
if (validateUserNameRules && !re.test(Model.userName)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Username must contain only letters, numbers and underscores.";
return (validationResult);
}
if (Model.password != "" && Model.password == Model.password2) {
if (Model.password.length < 6) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must contain at least six characters.";
return (validationResult);
}
if (validateUserNameRules && Model.password == Model.userName) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must be different from the Account Name.";
return (validationResult);
}
re = /[0-9]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one number (0-9).";
return (validationResult);
}
re = /[a-z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one lowercase letter (a-z).";
return (validationResult);
}
re = /[A-Z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one uppercase letter (A-Z).";
return (validationResult);
}
} else {
validationResult.ResultId = 2;
validationResult.Message = "Error: Please check that you've entered and confirmed your password.";
return (validationResult);
}
return (validationResult); //success password validation!!
};