I know this question is a lot easier than it seems, but I can't seem to get around it.

This is my current code and I cannot get it to properly check if the SSN number is in a proper format or not. It just says all is false. This is my current code:

<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>

What exactly am I doing wrong?

Recommended Answers

All 5 Replies

Your function works, but both the IF and the ELSE return an alert message that says its invalid.
The first part - the IF - should return in the alert box "Valid SSN"
I am assuming your input should be like this 123-45-1234

but do you need to tell the user the input is valid? Surely the alert should only be displayed if the input is invalid? So the if should return nothing. imho

Thanks for your reply. I want the input to be in the format as you said, xxx-xx-xxxx, but I do want it to give the error message showing that the input is improperly written. If it is properly written, I want it to say it is valid. How would I fix the If-else? statement so that it works?

Read what your alert code says!

[code]

 if(validSSN.test(document.getElementById("social").value))
      alert("Social is invalid.");

[/code]

that alert says Social is invalid when it should say Social is valid ...

I managed to figure it out. So my code works properly, the input just has to be written in the proper format with the dashes included.

NO !
You have to change the alert message when the SSN is entered correctly to tell them it is correct!
You're alert message is what is wrong, not the code checking things.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.