1

I would like to perform a whois-query if a user enters a valid domain. This query should be done using AJAX.

This script calls function checkDomain() always if the user types something into the form field:

js = jQuery.noConflict();
js(document).ready(function() {
    jQuery('#jform_domain').keyup(function() {
        checkDomain();
    });
});

function checkDomain() {
    var $this = jQuery(this);
    jQuery.ajax({
        url: '<?php echo JUri::root(); ?>/index.php',
        dataType: 'json',
        type: 'POST',
        data: {
            option: 'com_domaincheck',
            format: 'json',
            task: 'domain.checkDomain',
            domain: jQuery("#jform_domain").val(),
            '<?php echo JSession::getFormToken(); ?>': 1
        },
        success: function(response) {
            if (response.success) {
                console.log(response);
                jQuery("#test").html(response.message);
                // if (response.message == true) {} else {}
            } else {
                alert(response.message);
            }
        },
        error: function(data) {
            //console.log(data);
        }
    });
};

Now I would like to reduce unnecessary operations and start the script only, if the user entered a domain like:

example.com

It would be really, really, really cool, if the script would change inputs like www.example.com or http(s)://www.example.com to example.com aswell.

I'm a beginner in JS and jQuery, so please do not blame me for my bad knowledge - I try to learn ;-)

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
MyFault
  • 407
  • 5
  • 18
  • 2
    Regex is your friend here, probably. Have a look at this: http://stackoverflow.com/questions/10306690/domain-name-validation-with-regex – Joe Clay Apr 04 '16 at 09:53
  • Thank you very much. So if I use `^[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9].[a-z]{2,3}(.[a-z]{2,3})?(.[a-z]{2,3})?$` e.g., how could I use this as an condition in my case? – MyFault Apr 04 '16 at 10:06
  • shivgre's answer beat me to it - their code should do that for you :) – Joe Clay Apr 04 '16 at 10:22

1 Answers1

1

You need to use Regex for domain checking. I have used a basic regex, you can modify this regex or use another to suit your needs.

$(document).ready(function() {

    $regExDomain = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;

    $('#domain_name').on('keyup', function(){
        if($regExDomain.test($(this).val() ) ){
           console.info("valid domain");
        }else{
           console.info("invalid domain");
           return false;
        }
        console.log("Valid domain");
        checkDomain();//domain is valid so call your ajax function
    });

});
shivgre
  • 1,073
  • 1
  • 12
  • 29