0

I would like to create a regex pattern in javascript for a html text field that takes an address. So I only want the user to enter [a-z,A-Z,0-9] and only these symbols [,#-.] I also want to prevent the user from sending an empty string and the maximum number of characters to be less than 100.

This is the html <input>:

<input type="text" id="addy" maxlength="100"/>

I'm new to javascript, so I do not know how to create a function that will enable the regex patterns to be adhered to.

Thanks

EDIT

Following the recommendation by kolink I tried this:

 <input type="text" style="width:285px" placeholder="Enter A Precise Address" name="address0" id="address"
     pattern="[ a-zA-Z0-9,#.-]+" maxlength="100" title="Standard address notation only"/>

This now only works if the other <select> have not been selected. Otherwise it does not pick up the pattern attribute. However the exact same code works as expected on jsfiddle: http://jsfiddle.net/peD3t/7/ but not in the browser. This is the code in pastebin: http://pastebin.com/qQGJ4EK5

Thanks

2
  • Show your part of code for this task and people will help with it Commented Dec 28, 2012 at 21:49
  • Try something, post it here, and explain what is not working. This is not a do it for me forum. You'll learn when you've tried and failed and then succeeded Commented Dec 28, 2012 at 21:49

2 Answers 2

8

HTML5 gives you the pattern attribute, which allows you to require a certain pattern. In this case, you'd want pattern="[a-zA-Z0-9,#.-]+"

It doesn't matter that older browser don't support this, because you should always validate on the server side.

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

6 Comments

Thanks for suggesting the pattern attribute. However I cannot get it to work in my html as in my revised question.
What browser are you using?
Never mind, apparently the pattern is already anchored. Remove the ^ and $ from the start and end, and it should work.
even after removing ^ and $ it still doesn't rectify it
Can you update your code to show what you're trying now? A JSFiddle might be helpful.
|
0

$(document).ready(function () {

$('input').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9,#.-]/g, function(str) { return ''; } ) );
});

});

This will work.

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.