bry*_*bam 1 javascript forms validation xhtml
对于此示例,我们可以说我想在JavaScript中验证Google plus配置文件网址.
典型的Google加配置文件网址如下所示:
https://plus.google.com/115025207826515678661
Run Code Online (Sandbox Code Playgroud)
我基本上想确保至少在文本输入表单中键入的内容的开头是:
http OR https ://plus.google.com/
Run Code Online (Sandbox Code Playgroud)
怎么可以在JavaScript中完成?我找到的每个例子都只是一个简单的验证,如果它是一个URL.如果它包含特定URL的一部分,则不会.
您可以使用正则表达式/^https?:\/\/plus\.google\.com/
,但是,我宁愿使用DOM.
这应该做到......
var str = 'https://plus.google.com/115025207826515678661',
a = document.createElement('a');
a.href = str;
var valid = ((a.protocol == 'http:' || a.protocol == 'https:')
&& a.hostname == 'plus.google.com'
);
Run Code Online (Sandbox Code Playgroud)