1

I am practicing validations and trying to better my current progress. So far, I have created a script that collects a user's name when inputted and sees if it is valid with letters only submitted:

<script type="text/javascript">
    function checkName(){
        var validLetters=/^[a-z]+$/i;
        if(validLetters.test(document.getElementById("firstName").value))
            alert("Your name is accepted!");
        else
            alert("Your input contains invalid characters!");
    }

</script>
<form>
    <input type= "text" name="firstName" id="firstName">
    <input type= "button" value="Validate" onclick="checkName();">

</form>

I want to take it a step further and wanted to try this with numbers, specifically with something like social security numbers. How do you do a validation with numbers in a specific format, such as xxx-xx-xxxx. If it is invalid, I want to have an error message like I did for the name. Can someone guide me through this?

For now, I will have the above input and the social security input separate, but will fuse them together somehow when I figure it out.

--

I am trying to make sure that when I click the submission, it checks and sees if it is valid. This is the updated script that I have for SSN, I still need help with getting this to work:

<script type="text/javascript">
    function checkDgt(){
        var validSSN=/\d{3}-\d{2}-\d{4}/;
        if(validSSN.test(document.getElementById("social").value))
            alert("Social is invalid.");
        else
            alert("Invalid.");
    }

</script>
<form>
    <input type= "text" name="social" id="social">
    <input type= "button" value="Validate" onclick="checkDgt();">

</form>
Michael
  • 41,989
  • 11
  • 82
  • 128
CloudRookie
  • 29
  • 5
  • 9
  • I am not sure why the first word of my posts keep getting cut off, but I meant to say, "Hi, all." – CloudRookie Mar 20 '18 at 02:43
  • check it out https://stackoverflow.com/questions/38074856/social-security-number-input-validation – A l w a y s S u n n y Mar 20 '18 at 02:46
  • Just do a digit expression: `/\d{3}-\d{2}-\d{4}/` (3 digits, -, 2 digits, -, 4 digits) – Sterling Archer Mar 20 '18 at 02:47
  • 1
    Possible duplicate of [Social Security Number input validation](https://stackoverflow.com/questions/38074856/social-security-number-input-validation) – Sterling Archer Mar 20 '18 at 02:48
  • I tried to make the change, but I can't seem to get it to work.
    Also, how do I put a "-" between numbers? Like xxx-xx-xxxx
    – CloudRookie Mar 20 '18 at 03:00

0 Answers0