I have a text field where users enter a URL string, which cannot contain spaces or non-alphanumeric characters (if that's an accurate way of putting it).
Is there a way in Rails to restrict entry into the text_field itself so that spaces and characters like /":}{#$^# can be avoided?
Thanks a lot.
To clarify, the only characters that should be possible are letters and numbers.
The problem here is that URL strings can have slashes (/) and hash marks (#). So your regex is going to be quite complex to ensure the right portion of the field is filtered properly. But for plain character filtering, you can use simple regex to remove any non alpha-numeric characters.
Not sure about anything ruby-specific, but in straight javascript:
<html>
<body>
<form>
<input type="text" name="whatever" id="form-field" value="" />
</form>
</body>
<script type="text/javascript">
var oFormField = document.getElementById('form-field');
oFormField.onkeyup = function() {
oFormField.value = oFormField.value.replace(/[^a-zA-Z0-9]/, '');
}
</script>
</html>
You may use jQuery Tools Validator that uses HTML 5 tags to validate your forms.
This is a great way to validate your forms in an Unobscursive way without putting JS all over your forms :-).
Look at the "pattern" HTML 5 tag that allows you to validate a field against a Regexp.
http://flowplayer.org/tools/validator/index.html
Related
I have simple text input:
<div style="float:right" class="xField">
<input id="userLength" name="userLength"/>
<label style="margin-left: 3px;">m</label>
</div>
I need this input to only accept numbers and if the number is a whole number, it should only allow 5 characters i.e. 12345. If the number includes a fraction, it should then allow for 8 characters i.e. 12345,99.
I've tried adding maxlength to the input but that only works with one of these conditions at a time.
How can I accomplish this?
You could use the pattern attribute and provide a regular expression that supports your requirements.
for example (this does not forbid entering invalid data, but will mark the field as invalid while the pattern is not matched).
<div style="float:right" class="xField">
<input id="userLength" name="userLength" pattern="\d{1,5}(,\d{1,2})?" />
<label style="margin-left: 3px;">m</label>
</div>
All you need is this:
<form action="/" id="form">
<input pattern="\d{0,5}([,.]\d{1,2})?" title="max 5 digits and 2 decimals">
<button type="submit">submit</button>
</form>
This will allow the user to enter as many characters as he wishes, but upon form validation the form will fail if the pattern is not satisfied.
The pattern is a regex and reads as follows: from 0 to 5 numeric characters and optionally up to two decimals
Also, if the input should not be empty you can add a required attribute like this
<input ... pattern="" required>
This causes also a validation failure if the input is empty.
When the pattern is not met, the browser will show whatever is inside title="" to the user.
Play around with this fiddle so you can see how the validation errors are presented: https://jsfiddle.net/aqohfsrj/2/
Also, if you want to do something with the input value using javascript, I recommend binding to the form's submit event and not the button's click or input's enter-keydown events
document.getElementById("form").addEventListener("submit", e => {
// if this code is executed it means the validation passed, otherwise errors
// are displayed to the user and this code is not run.
e.preventDefault(); // <-- to avoid trying to use the form's action i.e. the browser will not navigate.
});
To understand the regex I used you can see this regex101 file:
https://regex101.com/r/aHLI6u/1
Finally a recommendation:
Try to avoid maxlength for validation; often times I have had to fill in a form online that asks for a credit card for example, and it is limited to maxlength="16" which at first sounds like a good idea, but what if you try to copy your credit card from a note you have or something, and it was stored as 5430-0000-1111-2222 (with dashes). It feels rude to disallow pasting more chars than allowed, when all the user wanted was to paste, then edit, then submit. I would let the user add as much content as they want, so they can edit in-place to remove parentheses (for phones), remove currency signs (for money), remove dashes (for credit cards) and validate after they have submitted the form.
I have some invalidly-nested HTML like:
<form class="form1" method="get">
<div>
<input name="field1">
</form>
<form class="form2" method="get">
<input name="field1">
</form>
</div>
Yeah, it's a mess, don't ask. The invalid nesting is causing problems somewhere else. jQuery I think is expecting a closing </div>, and only finding it at the last one. It's then treating the second <form> tag as invalid, and also discarding the closing </form> immediately above it, and assuming everything between lines 1 and 9 are one form.
If I output these to the console:
$('.form1).html() - all of line 1 - 9
$('.form2).html() - undefined
So what I'm trying to do is treat the whole thing as a string, and use regex to strip out form2. I'm expecting a regex something like:
formText.replace(/(<form\b[^>]*>)[^<>]*(<\/form>)/gi, "");
but I'm not sure how to reference the specific form with class=form2.
There's also a problem with it being a multi-line string.
Update: added more detail, outlining why jQuery's remove() method isn't working. jQuery only thinks there's one form unfortunately.
Don't use regex to parse HTML. Since you're using jQuery, just use .remove():
$(function() {
$(".form2").remove();
});
JSFiddle
I ended up using:
formText = formText.replace(/(<form\b[^>]*form2+.*>[\s\S]+<\/form>)/gi, "");
The [\s\S] matches all characters including \n and \r to cover the newlines.
I could probably have made the part of the regex dealing with the class name more specific so I knew it was the class and not some other random form with a similar, but in practice it didn't matter (there was only one instance of the 2nd form, with a very specific class name).
I'm using regex in javascript to validate a form. One of the form fields is a filepath so needs to end in a backslash.
Specifically, I'm using <input type="text" pattern="" /> and I want to fill out the Pattern attribute to validate it.
Now..
I understand you make a backslash literal by doubling up ie. \\
and I understand that you use the dollar ($) sign to find the end of the string.
So can anyone explain to me why $// and //$ don't work? And maybe give me an example of something that would work?
Thanks
I got it working if I match the entire input, like so .*\\$
Dropping the $ behaved ok too,
<form>
path: <input type="text" pattern=".*\\" title="ends in \">
</form>
(using Chrome 27)
You seem to be mixing up slash / with backslash \. A \\$ is different from a //$, and \\$ should work.
I try to make a RegEx for validating a form in javascript. The RegEx should only allow letters comma and punctuation. For instance I have this string:
Hi, this is a test of RegEx. Does it work
I've tried the following
/^[A-Za-z0-9,. ]{3,50}$/;
But it doesn't seems to work. Solutions?
Thanks!
EDIT:
This is my code:
<script type="text/javascript">
var RE_SSN = /^[A-Za-z0-9,. ]{3,50}$/;
function checkSsn(ssn){
if (RE_SSN.test(ssn)) {
alert("OK");
javascript:addAppointment(document.forms[0])
} else {
alert("NO!");
}
}
</script>
<div id="r">
<label for="receipt">Receipt</label><input type="checkbox" name="receipt" value="1"/>
</div>
<input type="button" value="Post it" onclick="checkSsn(this.form.content.value);"/>
You might need to escape the "." as that is a special character in regex.
/^[A-Za-z0-9,\. ]{3,50}$/;
Actually probably not. Try using http://www.regextester.com/ - I was able to get it to work anyway. Can you show us the full code for how you're implementing this?
if you want no punctuation at the beginning of the field:
/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/
this also allows spaces (one scenario for this is last name - De La Hoya, or O'Doul)
The below code works to only allow alphanumerics and spaces. However, I would like to also allow an accented character (Ã). How should the regex be modified?
Thanks
<html>
<head>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
$(function() {
$("#sub").bind("click",
function() {
$('#addText').val($('#addText').val().replace(new RegExp("[^a-zA-Z0-9 ]","g"), ''));
});
});
</script>
</head><body>
<div>Enter Text:</div>
<input id="addText" type=text/>
<input id="sub" type="button" value="Submit" />
</body></html>
If you only care about Latin-1 (Western European) letters, this should work:
[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff]
For other scripts (eg: Greek, Cyrillic, Thai letters, CJK characters, etc.) things get much more complicated, and it becomes safer to just forbid things like control characters, rather than trying to keep track of which characters are "letters".
If you just want to add this one character .. just add it in the regex
[^a-zA-Z0-9Ã ]
Keep in mind though that there might be complications as mentioned below so do follow the suggestion by Laurence Gonsalves
http://unicode.org/reports/tr18/
http://www.regular-expressions.info/unicode.html