2

I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.

var filter = "^[a-zA-Z''-'\s]{1,40}$";
        var label = $('#<%= txtName.ClientID %>').val();

        if ((label.length > 0) && (label!= '')) {
            if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
                if (label.match(/^\s$/)) {
                    alert("Please Enter a Valid name");
                    return false;
                }
                else {

                    $("#myModal").dialog('open');
                }
            }
            else {
                alert("Please Enter a Valid name");
            }
        }
        else {
            alert("Please Enter a Valid name");
        }

This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.

Thanks

4
  • Why don't you use an ASP .NET Regular Expression Validator or a custom validator ? That way, you get both client AND server side validation. Users can easily circumvent the JavaScript validation. Commented Jul 14, 2011 at 10:27
  • @Ranhiru Cooray - how do you know that he is using asp.net Commented Jul 14, 2011 at 10:30
  • @Ranhiru Cooray how do you know he is using .net? Commented Jul 14, 2011 at 10:30
  • Because he's using #<%= txtName.ClientID %> Commented Jul 14, 2011 at 17:01

2 Answers 2

1

It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)

/^\s$/ means "contains only one space"

I believe you are looking for

/^\s*$/ means "contains only zero or more spaces"

Sign up to request clarification or add additional context in comments.

Comments

0

you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.