Tore
Tore

Reputation: 119

How do I validate that each first letter in a name is in capital letters?

I have one input where the user writes her/his first and last name. I need to validate if both first and second name start with capital letters. Also need to handle more than two names.

I've tried this in my validation object. I realize that I get a if for each element while mapping, not sure how to write this correctly.

 nameCheck(value){
        let name = value.split(" ");
        name?.map(element => {
        if(name?.length > 0 && element[0] === element[0].toUpperCase()){
            return true
        }
        else{
            return false

            }
         }
        )
    }

I'm calling it like this:

const isValidName = validate.nameCheck(form.creator)
   console.log(isValidName)

Here isValidName ends up undefined. All my other validation-checks are simple if-statements which works fine.

Any idea how to tackle this?

Upvotes: 1

Views: 1446

Answers (1)

DecPK
DecPK

Reputation: 25408

You are not returning anything from the method nameCheck; But you are using map here, and if you return the value that map returns, then it will return an array of Boolean values.

const validate = {
  nameCheck(value) {
    let name = value.split(" ");
    return name?.map((element) => {   // change, Added return keyword
      if (name?.length > 0 && element[0] === element[0].toUpperCase()) {
        return true;
      } else {
        return false;
      }
    });
  },
};

const isValidName = validate.nameCheck("Test user");
console.log(isValidName);
const isValidName2 = validate.nameCheck("Test User");
console.log(isValidName2);

I don't think that you want to return an array; you just want to return a Boolean value that tells whether the name is valid or not.

So you can use every here as:

const validate = {
  nameCheck(value) {
    return value.split(" ").every((s) => s[0].toUpperCase() === s[0]);
  },
};

const isValidName = validate.nameCheck("Test user");
console.log(isValidName);
const isValidName2 = validate.nameCheck("Test User");
console.log(isValidName2);


EDITED: If there are multiple space between two word then you can filter out the empty string as

const validate = {
  nameCheck(value) {
    return value
      .split(" ")
      .filter(Boolean)
      .every((s) => s[0].toUpperCase() === s[0]);
  },
};

const isValidName = validate.nameCheck("Test user");
console.log(isValidName);
const isValidName2 = validate.nameCheck("Test      User");
console.log(isValidName2);


Validation for firstname and lastname

1) Using split and regex

const names = value.split(/\s+/);
if(names.length > 1) /* There are multiple names */

2) Using split and Destructuring

const [firstname, lastname] = value.split(/\s+/);
if (firstname && lastname) {
  /* Both firstname and lastname is present  */
}  

Upvotes: 3

Related Questions