I have created a quiz on javascript that once the user answers 4/6 or more correct they will then be asked for a First Name, Last Name and then be given a random 4 digit code. The part I'm having trouble with is making the FirstName and LastName letters only and also not allow and empty prompt.
Anyone know how i'd implement a Regex into this?
Anyone able to help?
function getAnswers(){
var amountCorrect = 0;
for(var i = 1; i <= 10; i++) {
var radios = document.getElementsByName('q'+i);
for(var j = 0; j < radios.length; j++){
var radio = radios[j];
if(radio.value == "1" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct number of answers: " + amountCorrect + " / 6");
if (amountCorrect <= 3){
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
else{
var firstname = prompt("Please enter your first name.");
var lastname = prompt("Please enter your last name.");
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function
close();
}
}
try this..
var alphaExp = /^[a-zA-Z]+ [a-zA-Z]+$/;
var firstname =prompt("Please enter your first name And Last Name","");
if (firstname ==null || firstname =="")
{
alert("First and last name must be filled out!");
location.reload(true);
}
else if (!firstname.matches(alphaExp))
{
alert("Name must contain letters only!")
location.reload(true);
}
else{ // your code here.
}
Try this regex:
^[A-Z][a-zA-Z]*$
This regex matches a string of letters:
Starting with the letter A-Z
Only allow letters from a-z and A-Z
It will not match an empty line or any other character.
/^[a-zA-Z]+$/
this will work for u.
Related
I'm validating a password following these criteria:
1•Letters and Numbers
2•Allow ‘!’, ‘?’, ‘.’
3•Min 1 capital letter
4•Min 8 chars
5•Max 16 chars
6•Min 2 numbers
7•Does not contain first name
8•Does not contain last name
This code works well for the first 6 conditions, still not able to validate 7 and 8.
function validatePassword(){
var inputs = document.getElementsByTagName('input');
var allowedInput = new RegExp("^(?=(.*\\d){2})(?=.*[A-Z])[a-
zA-Z0-9!?.]{8,16}$");
for(i = 0; i < inputs.length; i++){
if(inputs[i].type == "password"){
if(inputs[i].value.match(allowedInput)){
console.log("Pass Good");
}
else{
console.log("Only numbers, letters!,?,. allowed\n" +
"Between 8 - 16 chars\n" +
"Minimum one uppercase letter\n" +
"Minimum 2 digits\n");
}
}
}
}
Since you did not tag with regex here is another way:
var fnlc = firstname.toLowerCase();
var lnlc = lastname.toLowerCase();
var vallc = inputs[i].value.toLowerCase();
var hasname = (vallc.indexOf(fnlc) >= 0 || vallc.indexOf(fnlc) >= 0);
If you have your heart set on a regex because you love it so much ;), then just test the names separately:
var testNames = new RegExp(firstname+'|'+lastname, "gi");
var hasname = testNames.test(inputs[i].value); // true if found
Here is the javascript code to validate the first name and last name with regular Expression using Javascript
test() – This function is used to perform a regular expression match in JavaScript.
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('nameInput').value;
if(!regName.test(name)){
alert('Invalid name given.');
}else{
alert('Valid name given.');
}
<script>
function validate(){
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('name').value;
if(!regName.test(name)){
alert('Please enter your full name (first & last name).');
document.getElementById('name').focus();
return false;
}else{
alert('Valid name given.');
return true;
}
}
</script>
For valdation 7 and 8, you can use the Array.prototype.includes() and modify your code as shown below:
I'm assuming firstName and the lastName to be the variables you can get it from DOM using one of the Document.querySelector() or any other DOM manipulator.
function validatePassword(){
var inputs = document.getElementsByTagName('input');
var allowedInput = new RegExp("^(?=(.*\\d){2})(?=.*[A-Z])[a-
zA-Z0-9!?.]{8,16}$");
for(i = 0; i < inputs.length; i++){
if(inputs[i].type == "password" && inputs[i].includes(firstName) && inputs[i].includes(lastName)){
if(inputs[i].value.match(allowedInput) && ){
console.log("Pass Good");
}
else{
console.log("Only numbers, letters!,?,. allowed\n" +
"Between 8 - 16 chars\n" +
"Minimum one uppercase letter\n" +
"Minimum 2 digits\n");
}
}
}
}
I have a job. Unfortunately I got stuck. Could you help me.
Project:
Ask a sentence of user analysis.
Ask to see which letters you want the user to count the block.
Count the number of times that the letter occurs in the sentence.
A pop-up window and then type the following sentence: "The letter X times Y occurs in this sentence."
Must be use function!
I write this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
for (i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) {
alert("The letter " + letter + " occurs " + sentence.charAt(i) + " times in this sentence.")
}
}
return;
}
bernardTheLetterCounter();
You have to finish the counting (the inside of the loop) then print the result after the loop is done. Like this:
function bernardTheLetterCounter() {
var sentence = prompt("Please type in the phrase to be examined");
var letter = prompt("Please enter the letters were looking for.");
var count = 0; // the counter (initialized to 0)
// use var i instead of i (to make i local not global: this is just an advice)
for (var i = 0; i <= sentence.length; i++) {
if (sentence.charAt(i) == letter) { // if it is THE LETTER
count++; // increment the counter (add 1 to counter)
}
}
alert("The letter " + letter + " occurs " + count + " times in this sentence."); // use counter to print the result after the counting is done
// the return here has no meaning
}
bernardTheLetterCounter();
What you was doing is printing a message every time the letter is found (which is ugly for the user, especially if the count of that letter is big).
The function in this example can be re-used and tested. (ps. the for-loop is not a functional way of solving your problem).
var sentence = prompt("Please type in the phrase to be examined:");
var letter = prompt("Please enter the letter you are looking for:");
function countLettersInString(source, letterToFind) {
return source
.split('')
.filter(function(letter) { return letter === letterToFind; })
.length;
}
console.log([
'letter', letter,
'was found', countLettersInString(sentence, letter),
'times.'
].join(' '));
I working on a form but I have some troubles with the last if statement ( it's not working.
count is global and start as 0, for each field with the correct character filled in this will happen: count = count+1;
but if I clicked submit and leave 2 fields with not the correct character
( that should be count = 6 ) it doesn't give me an alert but skips it
this is how it should be.
check if password equals confirm_password
check if fields or not empty
check if fields have the correct characters ( count start as count = 0 , foreach field that is correct it it goes count = count +1,
in totaal it can get 8 but at 6 it still keeps submitting).
function validateForm() {
var fields = ["voornaam", "achternaam", "Email", "Wachtwoord", "Herhaal_Wachtwoord", "Straatnaam", "Huisnummer", "Postcode", "Woonplaats", "Telefoonummer"];
if (pass1.value !== pass2.value) {
alert("Wachtwoord komen niet overeen");
return false;
}
var l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
if (count < 8) {
alert("iets is niet goed ingevuld");
return false;
}
}
You have returned the false boolean before you have given the alert prompt! Just change the last if statement like this:
if (count < 8) {
alert("iets is niet goed ingevuld");
return false;
}
This is the regexp:
$("#newpassword").keyup(function(e) {
var htm = "";
var pass = this.value;
var length = this.value.length;
if (pass) {
var score = 0;
if(length >= 8 && length <= 16) { //PASSWORD MIN/MAX NUMBER OF CHARACTERS
var upper = /[A-Z]/;
var lower = /[a-z]/;
var number = /^[0-9]+$/; //PATTERN FOR NUMBERS
var schar = /[!##$%^&*?_~+-=<>]/;
//LOOPS THROUGH PASSWORD TO CHECK FOR AT LEAST ONE OF EACH PATTERN
for (i = 0; i < length; i++) {
if (pass.substr(i, 1).match(upper)) {
var uletters = true;
score ++;
//AT LEAST ONE LETTER EXISTS
}
if(pass.substr(i,1).match(lower)) {
var lletters = true;
score++;
//AT LEAST ONE LETTER EXISTS
}
if(pass.substr(i,1).match(schar)) {
var schar = true;
score++;
}
if(pass.substr(i, 1).match(number)) {
var numbers = true;
var schar = false;
//AT LEAST ONE NUMBER EXISTS
score++;
}
}
}
}
});
The any two condition is true means password is ok, but the above code if(numbers == true && schar == true) user type only number display password ok.
Please help me what is the problem in my code.
You don't need to iterate over each character of your password, just do the following:
score += upper.test(password)?1:0;
score += lower.test(password)?1:0;
score += number.test(password)?1:0;
score += schar.test(password)?1:0;
(test returns true or false) and check the score afterwards.
In general it's recommendable not to be too restrictive about the users password. It seriously harms the user experience if they are told to how their password should look like. You can make it a recommendation though. (E.g. display a bar: weak (red) - strong (green) password. This is much more motivating than harassing the user with any error messages.) Let them pass on score 2 and higher.
You can probably use RegExp.test() or RegExp.exec() to "find" a regex match within your string, rather than iterating the characters yourself.
function validatePwd (pwd) {
if (pwd.length < 8)
return false;
if (pwd.length > 16)
return false;
var upperPatt = /[A-Z]/;
var lowerPatt = /[a-z]/;
var numberPatt = /[0-9]/; // FIXED -- this is a better pattern for numbers.
var scharPatt = /[!##$%^&*?_~+-=<>]/;
score = 0;
if (upperPatt.test( pwd))
score++;
if (lowerPatt.test( pwd))
score++;
if (numberPatt.test( pwd))
score++;
if (specialPatt.test( pwd))
score++;
// don't make it too hard for the poor user, please..
// -- they have to type all this horrible rubbish.
if (score < 3) {
return false;
}
// OK.
return true;
}
I will flash a scrambled word and then the user will type in what the scrambled word is.
So far I have this code. This is for shuffle and display.
document.getElementById("shuffle").value = shuffle(document.getElementById("word").value);
var shuffledword = document.getElementById("shuffle").value;
var z = shuffledword.split("").join(' ');
var x=document.getElementById("demo");
x.innerHTML=z;
var str=document.getElementById("demo").innerHTML;
var n=str.replace(charcode,"...");
document.getElementById("demo").innerHTML=n;
What I want is to restrict the user to input the same number letters as in the shuffled word. Example: the word is "DOOMED"; I want to make it so that the user cannot click the letter D and O three times, but only once or twice. Same for the other letters, depending on the number letters in the shuffled word.
It this possible?
// Set an object with each letters of the (shuffled) word and their count
var letters = {};
for (var i=0 ; i<word.length ; i++) {
var c = word.charAt(i);
if ( ! letters[c]) letters[c] = 1;
else letters[c]++;
}
...
function process_user_char(K) {
// When user enter letter K
if ( ! letters[K]) {
alert("You cannot enter " + K);
return false;
}
else {
letters[K]-- ;
return true;
}
}
....
// To check wether user entered all letters, returns Yes or No
function check_if_user_entered_all_letters() {
for (var o in letters) {
if (letters[o]) return "No";
}
return "Yes";
}
edit Added return true / false in process_user_char to integrate into onkeypressed.
Here is the jsfiddle.