Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript string validator failing to validate correctly using startsWith()

I have this very simple validator

if (!toString(aAccountNumber).startsWith('A')) {
      alert('AAccountNumber must start with the capital letter A');
      return;
    }

I then call this when pressing a button on a web page but not matter what I type in the input field, even starting with an A like A112233 it still fails and puts up the alert

What am I missing here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is not the right way to us toString, it must be called on the object to test, you were probably just getting undefined.

if (!aAccountNumber.toString().startsWith('A')) {
  alert('AAccountNumber must start with the capital letter A');
}

Also note that a text input value is already a string so you probably don’t need to call toString at all.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading