Validating HTML text box with javascript and regex - javascript

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

Related

What is the best way to make a Romaji to Japanese keyboard?

I am sorry if the below info seems irrelevant or lengthy.
TL;DR I am wondering what would be the best way to code an English
input to Japanese output keyboard.
So I recently started learning Japanese, and with that I started using websites and apps like WaniKani and Anki to help me remember Kanji (Borrowed Chinese Characters). WaniKani has a simple and really good interface for answering questions, while Anki is a flash Card system that lets you make and manage cards of whatever you want to memorize.
So I thought of an idea that would get me best of both the systems, and now I am making a website that takes data from my Anki deck and uses that to quiz me on my website with a WaniKani like interface.
So for those who don't know, Each Japanese Characters can be converted to English counterpart based on their phonetics,
For eg, つ --> tsu
This is called Romaji Translation. Google Translate and WaniKani (and a lot of other websites) use this to convert Standard English Keyboard Input to Japanese.
So, back to my question, I was wondering what would be the best way to convert English input
like, tsu to つ. At first I thought of going with regex and came up with this.
/((?:[aeiou])|(?:[kstpgzdnhpmr][aeiou])|(?:shi|chi|ji|tsu|fu|ya|yu|yo|wa|wo))/gm
The above regex just looks for patterns of Either only vowel or consonant + vowel or some special characters.
This one isn't complete yet, since it can't detect double consonants
kko --> っこ
Which is different from ko --> こ
Another thing it can't do is find patterns like
cho or chyo --> ちょ
This is a combination character. Which complicates things a lot more.
If there's another better way of making it happen, please point it out or if I can somehow improve on the regex.
Also, there is one more thing,
Characters have, lets say, kind of an accent, called the Dakuten that changes the sound of the character, for example
 は Which is usually pronounced as Ha can be turned into ば which sounds like Ba, Notice those two little lines, most characters can have those.
Another form of it is the Handakuten, は Ha --> ぱ Pa.
So the above combination and double consonants apply to these accented characters too.
So I came up with a solution to convert the normal character to the accented one, by assigning a key to shuffle through the different forms of that word.
An example,
const keyboard = $(".keyboard");
keyboard.on("keydown", function(event) {
if (event.key == " ") {
// Disables the space key.
event.preventDefault();
var string = $(this).val();
// Position of the text cursor.
var caretPos = $(this)[0].selectionStart;
// If there is no character before the caret.
if (caretPos == 0) return false;
// String Operation
const invert = (char) => (/[a-z]/.test(char) ? char.toUpperCase() : char.toLowerCase());
var newString = string.slice(0, caretPos - 1) + invert(string[caretPos - 1]) + string.slice(caretPos, string.length);
$(this).val(newString);
// Sets the cursor after the changed character (its older position after being reset by the val()).
$(this)[0].setSelectionRange(caretPos, caretPos);
}
});
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
input {
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<input id="first_name" type="text" class="validate keyboard" autocomplete="off" autocapitalize="off" />
<label for="first_name">Kanji</label>
</div>
Set the Caret after any charcter in the text box and press the Space Key.
</div>
</form>
</div>
</div>
</body>
</html>
All it does is find the character before the caret and change it to Uppercase or Lowercase.
Instead of changing cases, it will traverse an array of the different forms the character that is before the caret.
This project just uses JQuery 3.6
and Materialize for CSS.
Thanks for Reading through all that. And I appreciate any and all replies.
Please tell me if I missed something.
Found exactly what I needed.
wanakana.js
It is sponsored by WaniKani creators.
wanakana also comes as a npm package
npm i wanakana

how to resolve the bug in the decimal validation code?

it will for 21.22 or 1.11 or something..
but the error is it will allow dot in front of digit and it allow multiple dot for example 123.2.2
<HTML>
<HEAD>
<script type="text/Javascript">
function testNum(inval)
{
var ex = /^\d*(?:\.\d{0,2})?$/;
if(ex.test(inval.value)==false){
inval.value = inval.value.substring(0,inval.value.length - 1);
}
}
</script> </HEAD> <BODY>
<input type="text" id="" onkeyup="testNum(this);" />
</BODY>
</HTML>
Change \d* to \d+ (+ is the equivalent of {1,}) to be sure to have at least one digit before your dot.
As for the multiple dot problem, no it doesn't match several dots.
Also, you may want to change your \d{0,2} to \d{1,2}, it doesn't really have any sense to match 12. for example.
It doesn't seem to allow multiple dots for me, but the \d* means that the starting digit(s) is (are) optional.
/^\d+(?:\.\d{0,2})?$/

Regex to test at least one number,can be alphanumeric,and should allow some special character

I am writing a regex for zipcode for following requirements.
It must contain at-least 1 number;
It could be alphanumeric;
Only special character allowed would be -, space and/or #.
Though it seems very simple,but I couldn't write it successfully. I am newbie to regex and not having smooth time with regex.
Please suggest solution.
Something like this?
/^(?=.*\d)[a-zA-Z\d #-]+$/
Just Try With The Follwoing Example :
HTML Part :
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var zipcode_expression = /^(?=.*\d)[a-zA-Z\d # ,-]+$/;
if (zipcode_expression.test($.trim($('#zipcode').val())) == false){
alert('invalid zipcode');
}
});
</script>
<input type="text" name="zipcode" id="zipcode" value="jo h,n1#-">
I think this may help you to resolve your problem.

RegEx in javascript. Allow only letters, comma and punctuation

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)

Restrict characters entered into a text_field

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

Categories

Resources