Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    32
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Reformat number after input.

    I'm trying you have the number entered be reformatted to add dashes after validation. But it is not working. Any suggestions?
    Code:
     function validateField ()
    {
    	var rgEX = /^(\d{2}[-]?)(\d{2}[-]?)(\d{3})$/;
            if ( ! rgEX.test( this.value ) )
            {
            	this.value = '';
     		alert("not a vln");
    	} else {
        this.value = str.replace(this.value,' $1- $2- $3')
    }

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,585
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Well, since you made the dashes optional in the RegExp, I would do it this way:
    Code:
     function validateField ()
    {
        var val = this.value.replace(/\D/g, "" ); // zap all NON-digit characters
        if ( val.length != 7 )  /* then there must be 7 digits exactly */
        {
            this.value = '';
     	alert("not a vln");
            return false; // ?? may not be needed, can't hurt
        } 
        this.value = val.substr(0,2) + "-" + val.substr(2,2) + "-" + val.substr(4);
        return true;
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •