0

I am using jquery mask plugin https://igorescobar.github.io/jQuery-Mask-Plugin/

i want to validate the field ipaddress if the user enter 192.3.4. and forgot to put value after . then i want to validate the text input box then when the user click on the save button

Here is my Html

<input type="text" class="form-control ip_address" placeholder="*IP Address">

and here is my jquery for the plugin mask

$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
       translation: {
                      'Z': {
                            pattern: /[0-9]/, optional: true
                           }
                  }
});

and here is how i want to validate the user on burron click

$('.btnsaveForm').on('click', function(e) {
                    e.preventDefault();
                     var ip = $('.ip_address').val();
                     if(ip){
                        alert('ip address');
                     }else{
                        alert('not an ip address');
                     }


            });

Kindly help me Thanks

1
  • just want to explain the if(ip) the ip address format is true then show success message other wise show error message Commented Jul 19, 2015 at 8:33

1 Answer 1

1

You may try a RegExp as below.

$('.btnsaveForm').on('click', function(e) {
    e.preventDefault();
    var ip = $('.ip_address').val();
    if(/^\d+\.\d+\.\d+\.\d+$/.test(ip)) {
        alert('valid ip address');
    }else{
        alert('not an ip address');
    }
});
  • \d+ => match numbers only
  • \. => match a .
  • ^ => input start point
  • $ => input end point

Edit: You may write a basic plugin like below.

(function ( $ ) {

    $.fn.isIpv4 = function() {
        return /^\d+\.\d+\.\d+\.\d+$/.test( $(this).val() );
    };    
}( jQuery ));

Use it as:

var ip = $('.ip_address'); // no val() here!
if( ip.isIpv4() ) {
    alert('valid ip address');
}

Edit: As per your last comment, you would be better off using a function like below as a jQuery plugin is not meant for this.

function isIpv4(ip) {
    return /^\d+\.\d+\.\d+\.\d+$/.test(ip);
}

var ipAdd = $('.ip_address').val();
if( isIpv4(ipAdd) ) {
    alert('valid ip address');
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Ishettyl can you kindly provide me the plugin solution if you have any it will be so help full this regex is working but i want to prefer the plugin solution. Thanks again
Thanks kindly let me test it
@Ishettyl if i want to pass value to the isIpv4() using $('.ip_address').val(); how can i do that can you please help me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.