JavaScript form validation 2 letters 1 number - javascript

I'm trying to make a validation for my form with JavaScript. This is what I have done so far, and it works, but in the input "klassekode" needs to start with two letters and then one number.
My html code
<form class="form1" method="POST" id="registrerFagSkjema" action="registrerklasse.php" name="registrerFagSkjema" onSubmit="return validerRegistrerFag()">
Registrer klasse <br> <br>
Klassekode <br>
<input value="" type="text" name="fagkode" id="fagkode" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"
onChange="endreTilStoreBokstaver(this)"/ /><br>
Klassenavn <br>
<input value="" type="text" name="klassenavn" id="klassenavn" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()" />
<input value="Registrer Klasse" type="submit" name="submit" id="submit" >
<input type="reset" value="Nullstill" id="reset" name="reset" onClick="fjernMelding()">
</form>
<div id="melding"></div>
My JavaScript code
function validate()
{
var klassekode = document.getElementById("klassekode");
var klassenavn = document.getElementById("klassenavn");
var feilmelding="";
//var firstTwoLetters = document.getElementById("klassekode").substring(0,2);
if(klassekode.value.trim()=="")
{
//alert("blank");
feilmelding="Fyll ut Klassekode";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassekode.style.border = "solid 1px red";
return false;
}
else if ( klassekode.value.trim().length!=3)
{
//alert("klassekode for lang");
feilmelding="Klassekode må kun være 3 bokstaver";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else if (klassenavn.value.trim()=="" )
{
//alert("blank");
feilmelding="Fyll ut Klassenavn";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else { return true;}
}

You got the hang of substring, and you can use that the newer method isNaN (Not a Number) and divide your third character with 1. If it's a letter, isNaN will return "true" and if it's a number, it will return "false".
I would, however, recommend you to learn regular expressions, as it will benefit you tremendously in the future.
You basically create a pattern and then test a string against that pattern. If you find a match, then it's correct. I made a snippet below to demonstrate:
function validateInput() {
let inputElement = document.getElementById("namn");
let divElement = document.getElementById("comment");
var message = "not true";
let inputValue = inputElement.value.trim();
let pattern = new RegExp(/^[a-zøæ]{2}\d{1}/, "i");
if (isValid(inputValue, pattern)) {
message = "true"
}
divElement.innerHTML = message;
}
function isValid(str, pattern) {
return str.match(pattern);
}
<input id="namn" type="input" value="">
<input type="button" onclick="validateInput()" value="Validate" />
<div id="comment"></div>
This row needs explanation:
let pattern = new RegExp(/^\d{1}[a-zøæ]{2}/, "i");
The regular expression contains expressions that can be stringed together:
^: start at the beginning of the string.
[a-zøæ]{2}: 2 characters must be between a-z or contain ø or æ.
\d{1}: next following 1 character must be a digit.
The flag "i" makes the a-z case insensitive. Another way would be to don't add a flag, and instead write [a-zA-ZøØæÆ]

Regex to the rescue. You can add another else if statement as per the following:
else if (klassekode.value.trim().length !== 3) {
// after checking whether the string length is 3 characters...
} else if (!klassekode.value.trim().match(/^[a-z]{2}\d/i)) {
// apply validation warning styles
return false;
}
An explanation of the Regex:
^ - asserts position at the start of the string
[a-z] - matches an alphabetic character
{2} - matches exactly twice
\d - matches a digit (0-9) once
i - case insensitive match
I am not checking the string length again because your previous condition accounts for it.
Ensure to trim() the value before using it (e.g. before sending it to the backend for processing, etc.), because otherwise the leading/trailing spaces will be retained.

Related

Javascript Regex - get variable from sentence

I want create simple AI for youtube in javascript. I want to write into input string like "Find Pranks on youtube". And that word "Prank" is variable... Everyone can write whatever thay want,but it must be sentence "Find 'something' on youtube". I tried to create regex, but it's to hard for me. Is it posible to do this like that?
The regex I tried is: \\Find\s\[abc]\s\\on\\youtube/i;
HTML Code:
<input type="text" id="uq" class="input auto-size"/>
<button id="button" onclick="question();" class="button" href="javascript:;">Ask</button>
Javascript Code:
function question()
const findonyoutube = /(?<=find)(.*)(?=on youtube)/gm;
var str = document.getElementById('uq').value;
if(findonyoutube.test(str))
{
alert(findonyoutube.exec(str)[0]);
}
}
Not working, it return Uncaught TypeError: Cannot read property '0' of null
To capture anything in between two words you can use:
function getVariable() {
const regex = /(?<=Find)(.*)(?=on youtube)/i;
let input = document.getElementById('myInput').value;
let match = regex.exec(input);
if(match) {
document.getElementById('debug').innerHTML = match[0];
return match;
} else {
return -1;
}
}
<h4>Example: Find ponies on youtube</h4>
<input type="text" id="myInput" />
<button onclick="getVariable();">Get Variable</button>
<br><br><hr>
<h3 id="debug"></h3>
It uses a positive lookahead and lookbehind to achieve this.

How to restrict the input for the html textbox with regex expression?

I'm a new learner of javascript.
So I have this html textbox.
<form method="get" id="form" action="number.php">
<p><input type="text" id="number" name="number" value="0,0" size="4"/></p>
</form>
And with javascript (not jquery), a regex expression and without changing the html code, I only want to allow an input of positive numbers or a pos. number followed by a comma followed by only one number after comma.
E.g. 5 or 23 or 141 or 0
E.g. 15,9 or 0,0 or 356,4 or 77,7
This is how my javascript function looks like but I am not sure how to call the function for the input of this textfield "number". And not sure if my regex is correct.
number.onkeypress = function validate(s) {
var rgx = /^\d+(,\d{1,1})?$/ ;
if(rgx.test(s)) {
return true;
}
else {
return false;
}
}
So my 2 questions are:
How can I check with a regex-function the input for the textbox, so only numbers and one comma is allowed?
Is my regex expression correct?
You try this
<p><input type="text" id="number" name="number" value="0,0" onblur="javascript:validate()" size="4"/></p>
<script>
function validate() {
var numberVar = document.getElementById("number");
var rgx = /^\d+(,\d{1,1})?$/;
if(!rgx.test(numberVar.value)) {
numberVar.value = "";
numberVar.focus();
}
}
</script>

Check if input is only alphabets in javascript using IF ELSE statement

I have an input field for which I need to make sure the input is only and only characters from the alphabet, with no:
numbers
special characters
number + alphabet combinations
I want to do this using if else statement only. So far the code is:
HTML:
<form id="myform" onsubmit="return check();" >
<input class="input" type="text" name="firstname">
And JavaScript is:
function check() {
var x = document.forms["myform"]["firstname"].value;
if (x == null || x == ""){
myform.action="firstnameerror.html";}
if (isNaN(x)) {
myform.action="lastname.html";
} else {
myform.action="firstnameerror1.html"
}
}
You can check it using regular expressions (RegExp), specifically with the .test() function:
if(/[^a-zA-Z]/.test(x))
// code to throw error
This will run the code to throw an error if any non-alphabetic character is contained in x.

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

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