最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Only letters and numbers allowed - Stack Overflow

programmeradmin1浏览0评论
    function f_check_NumOrLett(form){    //Only letters and numbers allowed  

        var text = form.bucketname.value;
        alert(text);

        var filter = /^[A-Za-z0-9]+$/;
        if (filter.test(text)) {
            form.submit(); 
        } else {
            form.bucketname.select();
            alert("Only Allow letters and numbers!");
        }
    }  

When I use this function, alert(text) can work, but it cannot neither submit the form or alert "Only allow letters and numbers" message. It seems it didn't excute IF condition.

    function f_check_NumOrLett(form){    //Only letters and numbers allowed  

        var text = form.bucketname.value;
        alert(text);

        var filter = /^[A-Za-z0-9]+$/;
        if (filter.test(text)) {
            form.submit(); 
        } else {
            form.bucketname.select();
            alert("Only Allow letters and numbers!");
        }
    }  

When I use this function, alert(text) can work, but it cannot neither submit the form or alert "Only allow letters and numbers" message. It seems it didn't excute IF condition.

Share Improve this question edited Dec 10, 2012 at 16:32 jzou117 asked Dec 10, 2012 at 16:24 jzou117jzou117 311 gold badge1 silver badge2 bronze badges 3
  • I don't get what you mean by "it cannot access into if condition". Can you make it clearer ? – Denys Séguret Commented Dec 10, 2012 at 16:26
  • what task are you trying to acplish? what have you done so far to try and solve the task? why didn't your approach work? – jbabey Commented Dec 10, 2012 at 16:27
  • 2 I don't see how it could fail between the first alert and the if blocks. Can you build a fiddle ? Are you sure you don't have intermediate code ? – Denys Séguret Commented Dec 10, 2012 at 16:35
Add a ment  | 

1 Answer 1

Reset to default 6

If you're cool with supporting new browsers and no legacy, you can use the new pattern attribute which is available on input elements (which I think you're using here)

Example:

<input type="text" pattern="[A-Za-z0-9]"/>

The pattern attribute takes a normal regular expression syntax. Additionally, you can add the required (boolean) attribute, which indicates what a form submit will only work if the pattern is fulfilled.

<input type="text" pattern="[A-Za-z0-9]" required/>
发布评论

评论列表(0)

  1. 暂无评论