1

I am creating a web page where I have an input text field in which I want to allow only alphabets,dots and spaces like "a b.c".

Space and dot allowed between consecutive words/characters but two consecutive spaces or dots are not allowed.

Allowed:- "abc def.xyz"

Not Allowed:- "abc def..xyz"

How can I do this using jQuery?

Sunil Chaudhary
  • 397
  • 1
  • 9
  • 31
  • Please try this with regex and pattern attribute in html5 – Chetan Jan 11 '17 at 10:03
  • Possible duplicate of [JS function to allow enter only letters and white spaces](http://stackoverflow.com/questions/19849189/js-function-to-allow-enter-only-letters-and-white-spaces) – demo Jan 11 '17 at 10:28

2 Answers2

2

I found the answer after some search.

we can use below regex to achieve this.

/^([\s.]?[a-zA-Z]+)+$/

Complete jQuery function:-

<script>
    $(document).ready(function () {
        $("input[type='text']").each(function () {
            $(this).blur(function (e) {                  
                if (Validate(this.id)) { }
                else { alert('invalid input'); }
            });
        });

        function Validate(evt) {
            var isValid = false;
            var regex = /^([\s\.]?[a-zA-Z]+)+$/;              
            isValid = regex.test($("#" + evt).val());
            return isValid;
        }
    });
</script>
Sunil Chaudhary
  • 397
  • 1
  • 9
  • 31
1

You can use the following pattern.It will allow only alphabets,dots and spaces
/^[a-zA-Z\. ]*$/
otherwise use prevent default method

 $(function()
        {
            $('#username').keydown(function(er)
            {
            if(er.altKey||er.ctrlKey||er.shiftKey)
            {
            er.preventDefault();
            }
            else
            {var key=er.keyCode;
            if(!((key==8)||(key==9)||(key==32)||(key==46)||(key>=65 && key<=90)))
                {
                     er.preventDefault();
                     alert("please enter only alphabets")
                }
            }
         }); });
user7397787
  • 1,410
  • 7
  • 28
  • 42