可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a input field where users can write a domain name that they wish for search for.
My domain search only support searches as: "something.com" or "something"
And it only support .com, .net, .org
That I want to do is validate the user input before the ajax call is made and display an error message if anything is wrong. Example if a user types: "asdasdasd.asdasd" or "wwwasd.asdasd" or "www.asdasd.dk"
#domainsearch is the input field #domanerknap is the search button
Here is my Jquery:
$(document).ready(function() { $('#domanerknap').click(function(e) { var doma = $('#domainsearch').val(); $('#contentajax').empty() .css("border", "1px solid #CCCCCC") .html('<p class="vent">Please wait...</p><p class="venter"><img src="../images/ajax.gif" /></p>'); $.ajax({ type: 'POST', url: 'http://localhost:3000/domain', data: { domain: doma }, success: function(msg){ $('#contentajax').html(msg); $('#contentajax').css("border", "none"); } }); }); });
回答1:
use a regex to check if the domain is valid. Such a regex might be :
/^(http(s)?\/\/:)?(www\.)?[a-zA-Z\-]{3,}(\.(com|net|org))?$/
Then before you send the ajax call, check to see if the input matches the regex :
$(document).ready(function() { $('#domanerknap').click(function(e) { var doma = $('#domainsearch').val(); if(!/^(http(s)?\/\/:)?(www\.)?[a-zA-Z\-]{3,}(\.(com|net|org))?$/.test(doma)) { alert('invalid domain name'); return false; } $('#contentajax').empty() .css("border", "1px solid #CCCCCC") .html('<p class="vent">Please wait...</p><p class="venter"><img src="../images/ajax.gif" /></p>'); $.ajax({ type: 'POST', url: 'http://localhost:3000/domain', data: { domain: doma }, success: function(msg){ $('#contentajax').html(msg); $('#contentajax').css("border", "none"); } }); }); });
回答2:
Use the pattern as shown below. To construct this pattern, I used the following rules:
- The domain must not contain a protocol
- Only alphanumeric characters and hypens are a valid domain name
- Sub domains are allowed
- Top level domain must be either of the following:
com net org
I have also included a dynamic match, so that protocols and paths are automatically omitted when input.
var domainPattern = /^(https?:\/\/)?((?:[a-z0-9-]+\.)+(?:com|net|org))(?:\/|$)/i if(doma.match(domainPattern)){ doma = doma[1]; //Get the domain parth $.ajax(...); //Valid }
回答3:
if( !doma.match(/^[a-z0-9_-]+(\.(com|net|org))?$/i)) { /* error stuff here */ else $.ajax(...);
Something like that, I would imagine, going by the examples of valid input you gave.
You can also put the part between the /.../
in the pattern
attribute of the input
element, and supporting browsers will match it before even allowing a submission.