Regular expression on textarea - javascript

I'm having a bit of trouble validating a form I have, I can check for only letters, numbers and a full stop ("period") in a single text input, but I can't for the life of me get it to work at all on a textarea field.
in my validation I have this:
var usernamecheck = /^[A-Za-z0-9.]{5,1000}$/;
the validation I've tried that doesn't work on the textarea ($ITSWUsers) is:
if(!document.all.ITSWUsers.value.match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
however, the following on a 'input type="text"' works just fine on the same form
if(!document.all.SFUsersName1.value.match(usernamecheck))
{
alert("Usernames can only contain letters, numbers and full stops (no spaces).");
return false;
}
I need it to validate usernames, 1 name per line
e.g.
John.smith
Peter.jones1
these are both OK but the following wouldn't be:
John Smith
David.O'Leary
3rd.username
any help/pointers with this would be greatly appreciated
(I only know basic html/php/javascript)

To validate line by line, I'd use the split function to turn each line into an array. Then, loop through the array and run your RegEx on each line. That way, you can report exactly what line is invalid. Something like this:
<textarea id="ITSWUsers"></textarea>
<button onclick="Validate()">Validate</button>
<script>
var usernamecheck = /^[A-Za-z0-9]{5,1000}\.[A-Za-z0-9]{5,1000}$/;
function Validate()
{
var val = document.getElementById('ITSWUsers').value;
var lines = val.split('\n');
for(var i = 0; i < lines.length; i++)
{
if(!lines[i].match(usernamecheck))
{
alert ('Invalid input: ' + lines[i] + '. Please write the usernames in the correct format (with a full stop between first and last name).');
return false;
}
}
window.alert('Everything looks good!');
}
</script>

I'd trim the input from the textarea using JQuery (or a JS function), and then use this regex:
/^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/
Like so:
function testFunc()
{
var usernamecheck = /^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/;
if(!$.trim(document.all.ITSWUsers.value).match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
}
<textarea id="ITSWUsers" cols="50" rows="10">
John.smith
Peter.jones1
</textarea>
<button onclick="testFunc()">Click Me</button>
See it working here:
http://jsfiddle.net/DkLPB/

Related

Beginning Javascript form validation

this is my first time posting.
I'm in a beginner Javascript class with the following assignment:
"Students are required to enter into a text box their course information in the following format:
AAA.111#2222_aa-1234
Your Web page will ask the user to type their information in a text box. The user will then click a form button named validate. If the format is correct a message will be generated below the button that reads "Correct Format". If the format is incorrect a message will be generated that reads "Incorrect Format". "
After my first attempt, I got the following feedback:
"You do not need a form for this assignment .You only need a text box and a button. Place your function on your button (onClick event). You only need one function for this assignment.  Your function should include getting the users input from the text box. You can use getElementById() and .value it should also include the regular expression, and what to so if it is correct or wrong."
So far I have the following:
function isValid(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return (myRegExp.test(text);
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src = "registerFourth.js"></script>
</body>
</html>
So sorry if I am not posting this correctly. My code is telling me I have a "Parsing Error: Unexpected Token" and when I fill in the text box and click Validate nothing happens. Thank you!
There are multiple issues in your approach.
1. Your isValid method expects text parameter which is not required
2. Your isValid method is recursive, I don't see why that is needed.
Please check below if it works for you.
function isValid() {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
var text = document.getElementById("course").value;
var match = myRegExp.test(text);
if(match) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format";
}
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
You had a few syntax errors:
return (myRegExp.test(text); should be return myRegExp.test(text);
isValid(document.getElementById("course".value) should be isValid(document.getElementById("course").value)
And finally, putting the return statemenet before the rest of your code defeats the whole purpose of the rest of your code. return breaks out of your current function, which means the if else statement is rendered useless.
function isValid(text) {
var myRegExp = "/([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/";
return myRegExp.test(text);
if (isValid(document.getElementById("course").value)) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type="text" name="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src="registerFourth.js"></script>
</body>
</html>
There are a couple of syntax as well as function construction issues with this.
You have a missing ) in 2 lines -
return (myRegExp.test(text);
and
if (isValid(document.getElementById("course".value) line
You are also returning the value before the conditional statement. So the block below, will never run. Returning a function value ends the function execution
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
Think about functions in terms of inputs and outputs and what function it performs.
For example,
/// this function only takes a string and tests if it matches the regex
/// input: string
/// output: true / false (boolean)
function testRegex(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return myRegExp.test(text)
}
/// this function runs when the button is clicked, calls the testRegex fn
/// and handles setting the output element
/// note: read about ternary conditional operators if confused about ?:
function isValid() {
const outputEL = document.getElementById("output")
const courseEl = document.getElementById("course")
outputEl.innerHTML = testRegex(courseEl.value) ? "Correct Format" : "Incorrect Format";
}
If you want to understand how the code is being executed -
the script tags loads your registerFourth.js which will contain the two functions I defined above - isValid and testRegex. Note that the functions are just defined and not executed yet
when you click the button, the isValid function starts executing
the isValid function gets the output element and course element
isValid then calls testRegex with the value of course element
now, testRegex runs with the value provided to it and returns (to the calling function, isValid is this case) a boolean value, based on if the value is valid
isValid is back in power and depending on the value testRegex sent it, it sets outputEl to CorrectFormat / Incorrect Format
isValid ends!
You miss a few closed brackets.
See updated RegExp .
Change document.getElementById("course".value) to document.getElementById("course").value
You use of return incorrectly, in my code no need return .
see full code :
function isValid() {
var text = document.getElementById("course").value;
var myRegExp = /^([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa|aa)-\d{4}$/;
document.getElementById("output").innerHTML = myRegExp.test(text) ? "Correct Format" : "Incorrect Format" ;
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
this line is invalid
return (myRegExp.test(text);
If you want to return if the test is true
if (myRegExp.test(text)) return;
You also need to close the () here with 2 more )
if (isValid(document.getElementById("course").value))
That should solve your syntax issues. Not your logic though...

See what changed inside TextArea with on change listener

I need a textbox, where everytime the text changes, I know what exactly has changed. I'm currently using a JQuery's listener for changes in my input element, and what I do is:
When the text changes
Get the text from the box a1 and compare to what I have in box a2.
If there are changes, log them into output textarea
Here is a Sample https://codepen.io/nikolaevra/pen/eeWWbo
I'm currently using the following diff library https://github.com/kpdecker/jsdiff, and it has O(NM) efficiency, which is a lot.
Is there a way to get the exact change that was made to the textarea using JQuery or anything like that? For example, if I had test in both a1 and a2 and then changed a1 to be testing, I want to see ing as the change that was made.
EDIT:
I tried playing around with the method a little bit and this is one problem that I found. When I run diff = "testing".replace("test",''); => ing just as required, but when I try diff = "testing a potato cannon".replace("testing potato cannon",''); => testing a potato cannon, where I only changed one character. This is a lot of overhead that I wanted to avoid. In that case, I would only want to know where the value has been changed and what it has been changed to. Not the entire tail of the string.
Consider that what you have in string a1 is the constant text and that what you have in string a2 is where you make changes.
let's just say that the value in a1 is "test";
Try this for your JavaScript:
var constValue = $('#a1').val();
$('#a2').change(function() {
var changingValue = $('a2').val(); // say the value entered is "testing"
console.log(changingValue.replace(constValue, ''); // gives you "ing"
}
This will give you the changed/entered (newly) value in string a2 and log it to your console.
The logic you use here is simple:
Read the value from string a2 and use the value in a1 to replace (if exists) in string a2, hence giving you the changed value. You need not use any libraries for this. JavaScript gives you this function called replace.
Do let me know if any more queries.
nikolaevra, have you tried using javascript's replace method? e.g diff = [value of a1].replace([value of a2],'');
You can use this method to achive what you are looking for :
function getDifference(a, b)
{
var i = 0;
var j = 0;
var result = "";
while (j < b.length)
{
if (a[i] != b[j] || i == a.length)
result += b[j];
else
i++;
j++;
}
return result;
}
Then you need to make a method to get the values from your textboxs and use it in your button onclick event, I used javascript, you can use jquery if you want :
function findDiff(){
var b1= document.getElementById("b1").value;//sky is blue
var b2= document.getElementById("b2").value;//sky is red
document.getElementById("result").value=getDifference(b1,b2);//red
}
https://jsfiddle.net/eu2kvfxo/
i hope this code will help you
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var arr_text1 = new Array();
var arr_text2 = new Array();
var i=0;
var text2nw="";
$('#a2').on('input',function () {
arr_text1 = $("#a1").val().split('');
arr_text2 = $("#a2").val().split('');
if (arr_text1[i] == arr_text2[i]) {
}
else {
$('#output').val($("#a2").val().replace($("#a1").val(), ""));
// $('#output').val(text2nw);
}
if ($("#a2").val() != '') {
i++;
}
else {
i = 0;
$('#output').val('');
}
});
});
</script>
</head>
<body>
<p>This is the original text:</p>
<textarea id="a1" rows="4" cols="50" type="text"></textarea>
<p>Change Text to something else here:</p>
<textarea id="a2" rows="4" cols="50" type="text"></textarea>
<p id="title">This are the changes that you made:</p>
<textarea rows="10" cols="100" id="output" for="title"></textarea>
</body>
</html>

JavaScript regular expression mobile phone number format

1.XXX-XXX-XXXX
2.XXXXXXXXXX
I would like to know the regular expression of the format.
Modifying the existing sources will yield results.
var regExp = /^01([016789]?)-([0-9]{3})-([0-9]{4})$/;
var regExp = /^01([016789]?)[0-9]{3}[0-9]{4}$/;
A statement to check the condition.
I wonder if the contact form is also correct.
var test is a text field that receives input.
if(!regExp.text) {
alert(""phone number format is not valid.");
document.getElementById('phone').focus();
return ;
}
I'm not quite sure what you are trying to achieve, but maybe this example helps:
https://jsfiddle.net/xu9fcbxt/
Notice: jQuery required
Code:
JS:
$(document).ready(function(){
var regExp = /^01[5-7][1-9]-[0-9]{3}-[0-9]{4}/;
$('#phone').focusout(function(){
var text = $('#phone').val();
if(!regExp.test(text)){
alert('not a valid phone number');
}
});
});
HTML:
<input id="phone" type="text" />
This would check if the number has a format like 0151-123-4567

Masking Password

I have an application that as part of a call, returns a JSON string which apart from other details include the password. Now, in this particular screen, when you're in view mode, I would like to show the password masked (*******) in a span, while if you click on the edit button, I show the password in an input field.
It is the first time I am using AngularJS for this, and tried to look if there's some filter that can help me in this, but didn't go too far. Is there some other service that I would be able to use to just mask the password and show it in a span?
Hi you can achieve this by doing :
//html
<span ng-show="showpassword" type="password">{{password | passwordFilter}}</span>
<input ng-hide="showpassword" type="password" ng-model="password">
<input type="checkbox" ng-model="showpassword" ng-checked="false">
//js file
app.filter('passwordFilter', function() {
return function(input) {
var split = input.split('');
var result = "";
for(var i = 0 ; i < split.length ; i++){
result += "*";
}
return result;
};
});
You could write a simple filter to mask a string into some repeated char:
function passwordMask(aString) {
return Array(aString.length + 1).join("*");
}
angular.module("someModule")
.filter("pwMask",function(){
return passwordMask;
});
Then you could just use {{password | pwMask}} in your angular expressions.

Only allow HTML field to start with certain words

Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/

Categories